【问题标题】:How to write data into Firebase Realtime Database?如何将数据写入 Firebase 实时数据库?
【发布时间】:2020-04-20 13:51:00
【问题描述】:

我正在尝试以 2000 毫秒的间隔将用户位置数据写入我们的 Firebase RDB。 控制台显示我们每 2 秒正确获取一次位置数据。但是,数据不会传输到我们的 Firebase RDB。

有谁知道如何解决这个问题?

tracking.page.ts

  // Start location watch
  watchLocation() {
    const options = {
      maximumAge: 15000,
      timeout: 5000,
      enableHighAccuracy: true,
    };
    this.isWatching = true;
    this.trackingId =  '-' + Math.random().toString(36).substr(2, 28);

    clearInterval(this.interval);
    this.interval = setInterval(() => {
    this.watchLocationUpdates = this.geolocation.getCurrentPosition(options);
    this.watchLocationUpdates.then((resp) => {

      this.geoLocations = resp.coords;
      this.geoLatitude = resp.coords.latitude;
      this.geoLongitude = resp.coords.longitude;
      this.geoAccuracy = Math.trunc(resp.coords.accuracy);
      this.timeStamp = resp.timestamp;

      this.geolocationService.insertUserGeolocation({
        trackingId: this.trackingId,
        latitude: this.geoLatitude,
        longitude: this.geoLongitude,
        accuracy: this.geoAccuracy,
        timeStamp: this.timeStamp,
        uId: this.uId
        });
          console.log(`User location data inserted in FB`, {
            trackingId: this.trackingId,
            latitude: this.geoLatitude,
            longitude: this.geoLongitude,
            accuracy: this.geoAccuracy,
            timeStamp: this.timeStamp,
            uId: this.uId
            });

      const position = new google.maps.LatLng(resp.coords.latitude, resp.coords.longitude);
      this.map.setCenter(position);
      this.map.setZoom(16);

      this.markers.map(marker => marker.setMap(null));
      this.markers = [];
        const latLng = new google.maps.LatLng(resp.coords.latitude, resp.coords.longitude);
        const marker = new google.maps.Marker({
          map: this.map,
          icon: {
            path: google.maps.SymbolPath.CIRCLE,
            scale: 13,
            fillColor: '#1AA0EC',
            fillOpacity: 1,
            strokeColor: 'white',
            strokeWeight: 2
        },
          position: latLng
        });
        this.markers.push(marker);
      });
    }, 2000);
}

geolocation.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment  } from '../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class GeolocationService {
  databaseUrl = environment.firebase.databaseURL;

  constructor(private http: HttpClient) {
    console.log('Hello OrganizationService Provider');
    console.log('OrganizationService: ', this.databaseUrl);
  }

  insertUserGeolocation(data) {
    return this.http.post(`${this.databaseUrl}/geolocations/.json`, data);
    console.log('insertUserGeolocation(data): this.insertUserGeolocation(data));
  }

【问题讨论】:

  • 您似乎没有在任何地方检查错误。您如何知道请求是否因某种原因失败?
  • console.log 不会抛出任何错误。所有位置数据都以正确的方式显示。但不知何故,它不会被转移到 RDB 中。
  • 您需要检查代码中的错误并将结果打印到控制台。您需要确定this.http.post() 是否失败。
  • 你的意思是这样? console.log(User location data inserted in FB, { trackingId: this.trackingId, latitude: this.geoLatitude, longitude: this.geoLongitude, accuracy: this.geoAccuracy, timeStamp: this.timeStamp, uId: this.uId });
  • 我不知道 API 是如何工作的,但是你应该做任何你需要做的事情来解决请求失败的问题。请编辑问题以包含检查错误的代码,如果有错误消息,请将其包含在您的问题中。

标签: angular typescript firebase firebase-realtime-database geolocation


【解决方案1】:

使用库AngularFire 比使用HttpClient 并执行http 请求更容易、更高效。

对于 rxample,您可以使用 push() 方法添加数据:

const itemsRef = db.list('items');
itemsRef.push({ name: newName });

https://github.com/angular/angularfire/blob/master/README.md#install

【讨论】:

  • 感谢您的回答。我也想过。但是我们将来可能想更改数据库(例如 Amazon Cloud),然后它就不能再与 AngularFire 一起使用了。还是我错了?对于我上面提到的问题,您是否也有解决方案?
  • 你能检查日志是否有任何错误,你是否使用了等于 true 的读写规则?
  • 我检查控制台是否有错误。一切看起来都很好。所有的 console.logs 都会显示出来。 Firebase 规则也是正确的。我想这与.then有关。我在实现 setInterval() 函数时将其从 .subscribe 更改。从那以后它就不再起作用了。
  • 你在哪里订阅你的代码?帖子返回一个 observable,您可以订阅并添加一个 console.log 来检查 wat 是否正在发生
  • 我在添加 setInterval() 函数之前订阅了。实施 setInterval() 函数后,订阅不再起作用。这就是为什么我将其更改为 .then。
【解决方案2】:

我刚刚找到了解决方案。请在下面找到代码。

this.geolocationService.insertUserGeolocation({
        trackingId: this.trackingId,
        latitude: this.geoLatitude,
        longitude: this.geoLongitude,
        accuracy: this.geoAccuracy,
        timeStamp: this.timeStamp,
        uId: this.uId
        }).subscribe((response) => {
          localStorage.setItem('lastLocation', JSON.stringify({
            trackingId: this.trackingId,
            latitude: this.geoLatitude,
            longitude: this.geoLongitude,
            accuracy: this.geoAccuracy,
            timeStamp: this.timeStamp,
            uId: this.uId
            }));
          console.log(`user location data inserted in FB`, {
            trackingId: this.trackingId,
            latitude: this.geoLatitude,
            longitude: this.geoLongitude,
            accuracy: this.geoAccuracy,
            timeStamp: this.timeStamp,
            uId: this.uId
            });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 2022-01-18
    • 2019-10-11
    相关资源
    最近更新 更多