TypeError: this.db.list(...).subscribe is not a function

TypeError: this.db.list(...).subscribe is not a function

我用 Firebase 开发了一个 Ionic 3.9 聊天,但出现以下错误:

TypeError: this.db.list(...).subscribe is not a function

这是我的代码:

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

@IonicPage()
@Component({
    selector: 'page-consersation',
    templateUrl: 'conversation.html',
})
export class ConversationPage {
    username: string = '';
    message: string = '';
    _chatSubscription;
    s;
    messages;

    constructor(public db: AngularFireDatabase,
        public navCtrl: NavController, public navParams: NavParams) {
          this.username = this.navParams.get('username');
          this._chatSubscription = this.db.list('/conversation').subscribe( data => {
            this.messages = data;
          });
        }

    sendMessage() {
        this.db.list<any>('/conversation').push({
            username: 'romain',
            message: this.message
        }).then( () => {
            // message is sent
        });
        this.message = '';
    }
}

你能帮帮我吗?

this.db.list('/conversation').subscribe( 中,您遗漏了 .list(...).subscribe(...

之间的内容

您缺少的是 .valueChanges().snapshotChanges()...您可以在 the AngularFire2 documentation here.

中了解差异

我通常最常使用 .valueChanges(),因此对于 .valueChanges() 的快速示例,您的代码将是:

this._chatSubscription = this.db.list('/conversation').valueChanges().subscribe( data => {
    this.messages = data;
);

EDIT - 更正了下面的代码。不应该设置一个等于整个.subscribe的变量...定义你的pointer/listener,然后单独订阅它。

this._chatSubscription = this.db.list('/conversation').valueChanges()
this._chatSubscription.subscribe( data => {
    this.messages = data;
);

第二次编辑 - 在 OP 作为答案发布的新错误消息之后。 这个新错误看起来是由于版本冲突引起的 - 查看

当您遇到以下错误时 polyfills.js:3 Uncaught TypeError: Object(...) is not a function...,请尝试以下代码:

this._chatSubscription = this.db.object('/conversation').valueChanges().subscribe(data => {
  this.messages = data;
});