Angular / Angularfire2找不到不同的支持对象

时间:2017-12-29 00:57:20

标签: angular rxjs angularfire2

我无法分配firebase db.list()返回变量

COMPONENT:

import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
//import { FirebaseListObservable } from 'angularfire2/database-deprecated';

@Component({
  selector: 'app-cadastrar-pessoa-lista',
  templateUrl: './cadastrar-pessoa-lista.component.html',
  styleUrls: ['./cadastrar-pessoa-lista.component.css']
})
export class CadastrarPessoaListaComponent implements OnInit {

  pessoas: AngularFireList<any[]>;

  constructor(db: AngularFireDatabase) {
    **console.log('antes...: ' + typeof this.pessoas); // == undefined**
    this.pessoas = db.list('pessoas');
    **console.log('antes...: ' + typeof this.pessoas); // == object**
  }

  ngOnInit() {

  }

}

ng serve有效,但组件没有,devtools中的错误是:

  

AngularFireList无法找到不同的支持对象&#39; [对象   对象]&#39;类型&#39;对象&#39;。 NgFor仅支持绑定到Iterables   例如Arrays

所以,documentation list() deals with a Generic type,只要我理解:

list<T>(pathOrRef: PathReference, queryFn?: QueryFn): AngularFireList<T> {
    const ref = getRef(this.app, pathOrRef);
    let query: DatabaseQuery = ref;
    if(queryFn) {
      query = queryFn(ref);
    }
    return createListReference<T>(query);
  }

发生了什么,我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:0)

db.list()检索Observable值(异步) - manual。因此,在获得subscribe()值之前,您需要pessoas

constructor(db: AngularFireDatabase) { }

ngOnInit() {
    let pessoasObservable = db.list('pessoas').subscribe(pessoas => {
        this.pessoas = pessoas;
    });
}

最佳做法告诉我们使用onInit()代替constructor() - link

答案 1 :(得分:0)

我认为问题的原因是你将dbReference返回给模板。尝试进行此修改

  pessoasRef: AngularFireList<any[]>;
  pessoas: Observable<any[]>;

  constructor(db: AngularFireDatabase) {

  this.pessoasRef = db.list('pessoas');
  this.pessoas = this.pessoasRef.valueChanges();