AngularFire2报错:database无list方法、AngularFireObject无push方法求助
解决AngularFire2中
list和push方法不存在的问题 嘿,这个问题是因为AngularFire2在5.x及以后的版本里彻底重构了数据库相关的API,旧的database.list调用方式和AngularFireObject的push方法都已经被移除啦,我来帮你把代码调整成最新的正确写法:
关键API变更说明
- 旧版本中通过
af.database.list()获取列表的方式,现在直接用af.list()替代 AngularFireObject是单个数据节点的类型,不支持push操作,只有列表类型AngularFireList才有push方法- 查询参数(比如
limitToLast)不再需要嵌套在query对象里,直接作为配置参数传入
修改后的完整代码
import { Component } from '@angular/core'; // 导入正确的列表类型:AngularFireList import { AngularFireDatabase, AngularFireList } from "angularfire2/database"; import { AngularFireAuth } from 'angularfire2/auth'; import * as firebase from 'firebase/app'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { // 将items的类型改为AngularFireList<any>,因为它是消息列表而非单个节点 items: AngularFireList<any>; name: any; msgVal: string = ''; title = 'app'; constructor (public afAuth: AngularFireAuth, public af: AngularFireDatabase) { // 直接调用af.list(),并传入查询参数 this.items = af.list('/messages', { limitToLast: 5 }); // 新版本推荐用authState替代auth.subscribe this.afAuth.authState.subscribe(auth => { if(auth) { this.name = auth; } }); } login() { this.afAuth.auth.signInWithPopup(new firebase.auth.FacebookAuthProvider()); } chatSend(theirMessage: string) { // 现在items是AngularFireList类型,可以直接调用push方法 this.items.push({ message: theirMessage, name: this.name.displayName || this.name.facebook.displayName }); this.msgVal = ''; } }
额外注意点
- 确保你安装的是最新版的AngularFire2和Firebase,如果版本不匹配可能还会有其他问题,可以重新安装:
npm install angularfire2 firebase --save - 我把
af.auth.subscribe改成了af.authState.subscribe,这是新版本里更规范的写法哦
内容的提问来源于stack exchange,提问作者Abdallah Abdillah
相关产品推荐
相关产品推荐

