类型“ Observable <{} []>”不可分配给类型“ AngularFireList <any>”

时间:2018-12-13 22:44:45

标签: angular firebase angularfire2

我正在遵循有关使用AngularFire2的tutorial

  

类型'Observable <{} []>'不可分配给类型'AngularFireList'。     类型'Observable <{}}]中缺少属性“查询”。

在查看this的一些参考资料之后的位置。还尝试在repo中执行相同的操作,但是仍然很不幸没有找到答案

以下代码:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';

@IonicPage()
@Component({
  selector: 'page-graph-sensor',
  templateUrl: 'graph-sensor.html',
})
export class GraphSensorPage {
  sensorData: AngularFireList<any[]>;

  constructor(public navCtrl: NavController, public navParams: NavParams, public firedb: AngularFireDatabase) {
    this.sensorData = firedb.list('/reading').valueChanges();
    console.log(JSON.stringify(firedb.list('/reading').valueChanges()));
  }

1 个答案:

答案 0 :(得分:0)

valueChangesObservable,因此如果不订阅,就不会取回JSON数据。我假设您想查看数据?

尝试跑步;

 this.sensorData: any[];


 firedb.list('/reading').valueChanges()
   .subscribe(sensorData => {
     this.sensorData = sensorData;
   });

此外,您不应该在constructor中运行此逻辑。相反,您应该在ngOnInit中加入。订阅时,您有责任取消订阅。一种简单的模式是退订ngOnDestroy

import { Component, OnInit, OnDestroy } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
import { Subscription } from 'rxjs/Subscription';

@IonicPage()
@Component({
  selector: 'page-graph-sensor',
  templateUrl: 'graph-sensor.html',
})
export class GraphSensorPage implements OnInit {
  sensorData$: Subscription;
  sensorData: any[];

  constructor(public navCtrl: NavController, public navParams: NavParams, public firedb: AngularFireDatabase) { }

  ngOnInit() {
    this.sensorData$ = firedb.list('/reading').valueChanges()
      .subscribe(sensorData => {
        this.sensorData = sensorData;
      });
  }

  ngOnDestroy() {
    this.sensorData$.unsubscribe();
  }
}