在angularfire2中收听集合的更新很容易。每当新项目被添加到集合中(或从集合中删除)时,我都希望也运行一个函数。这是一些示例代码::
let path = 'doc1/' + doc2 + '/doc3/';
this.varCollection = this.afs.collection(path);
this.var = this.varCollection.valueChanges(); //Do something here?
答案 0 :(得分:1)
valueChanges()
返回一个Observable,以便您可以这样订阅:
this.subscription = this.varCollection.valueChanges().subscribe((val) => {
this.var = val;
runSomeFunc();
})
如果您在模板中使用async
管道,或者只是想保持Observable,请尝试.map()
然后返回:
this.var = this.varCollection.valueChanges().map(_ => {console.log('value changed'); return _});
如果您需要文档的元数据,可以使用snapshotChanges()
:
this.subscription = this.varCollection.snapshotChanges().subscribe( //do something )