Ionic 2将AngularFire2列表用于ts文件

时间:2017-01-02 23:58:03

标签: firebase ionic-framework ionic2 angularfire2

如何在离子2中的ts文件中使用AngularFire2参考? (例如我参考了我的Firebase)

   this.courses=this.af.database.list('/CoursesList/2017/Software/A/SemA');

我想检查ts文件中的迭代(不是在HTML文件中)并对该数据执行某些操作。有可能吗?

我试着这样做,但我得到了错误 enter image description here

这是我的代码

  this.courses
  .subscribe(snapshots => {
    snapshots.forEach(snapshot => {
      console.log(snapshot.val());


    });

1 个答案:

答案 0 :(得分:1)

是的!有多种方法可以做到这一点。致电.list()会使用FirebaseListObservableObservable.push()和{{1}等方便的方法返回.set() .update()只是.delete() }。

最简单的方法是调用.subscribe()并迭代实际数组。

af.database.list('/songs').subscribe(songs => {
  // songs is the downloaded array
  // type could simply be any[] or whatever model you need
  this.songs = songs;
  // or you can forEach or whatnot
  this.songs.forEach(song => console.log(song));
});

更有利的方法是使用像Observable这样的.map()运算符:

af.database.list('/songs')
// Almost like a regular array map, but it emits for each item
// added over time
.map(song => {
  song.name = song.name.toUpperCase();
  return song;
})
.subscribe(songs => {
  // songs is the downloaded array
  this.songs = songs;
  // All the names will be in caps
  this.songs.forEach(song => console.log(song.name));
});

请确保您导入.map()运算符,否则它将无法运行!

import 'rxjs/add/operator/map`