使用 Angular 2 和 AngularFire 访问 Firebase 列表值

Accessing Firebase list values with Angular 2 and AngularFire

到目前为止,我已经能够将我的 CRUD 应用程序迁移到 Firebase。我可以列出、创建和删除新闻。不过,我正在为编辑而苦苦挣扎。

这是编辑组件。它获取路由参数的快照,该参数等于 Firebase 中该特定新闻的 $key 值。然后我将它连接到数据库列表:

import { Component} from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AngularFire, FirebaseListObservable } from 'angularfire2';

@Component({
  moduleId: module.id,
  selector: 'app-edit-news',
  templateUrl: 'edit-news.component.html',
  styleUrls: ['edit-news.component.css']
})
export class EditNewsComponent {
  noticia: FirebaseListObservable<any>;

  constructor(
    private route: ActivatedRoute,
    private af: AngularFire) { 
      this.news = af.database.list('news/'+this.route.snapshot.params['id']);
    }

}

我是 observables 的新手,但我认为有了这个我可以使用插值访问数据库的具体对象 {{news.title}} 显然,我错了。有帮助吗?

在 html 模板中供 EditNewsComponent 使用

{{(news | async)?.title}}    // you don't need '?' if it can't be null

可能你还需要改变

this.news = af.database.list('news/'+this.route.snapshot.params['id']);

this.news = af.database.object('news/'+this.route.snapshot.params['id']);

这样您访问的是对象而不是列表。

使用这个语法

noticia: firebaseListObservable<any[]>;
constructor(private db: AngularFireDatabase,public af:AngularFireAuth) {
     this.noticia = db.list('/news',{
       query: {
          orderByChild:'id'
              }
     });
   }