首页 > 解决方案 > TypeError: this.db.list(...).subscribe 不是一个函数

问题描述

我与 Firebase 进行了 Ionic 3.9 聊天,但出现以下错误:

TypeError: this.db.list(...).subscribe 不是一个函数

这是我的代码:

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 = '';
    }
}

你能帮我吗?

标签: javascriptfirebaseionic-frameworkchattypeerror

解决方案


this.db.list('/conversation').subscribe(你错过了和之间的.list(...)东西.subscribe(...

您缺少的是.valueChanges()或者.snapshotChanges()...您可以在此处阅读 AngularFire2 文档中的差异。

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

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

编辑- 下面更正了代码。不应该将变量设置为等于整个.subscribe...定义您的指针/侦听器,然后单独订阅它。

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

第二次编辑- 在 OP 作为答案发布的新错误消息之后。该新错误似乎是由于版本冲突引起的 - 请使用多种可能的解决方案查看此问题


推荐阅读