我有一个firebase数据库......所以它都是JSON。 我使用AngularFire2数据库检索数据...我正在阅读this教程...
这个问题的代码部分是:
noteList: Observable<Note[]>
constructor(public navCtrl: NavController, private noteListService: NoteListService) {
this.noteList = this.noteListService.getNoteList()
.snapshotChanges()
.map(
changes => {
return changes.map(c => ({
key: c.payload.key, ...c.payload.val()
}))
});
从这里开始,我想做两件事:
noteList
Ex:myVar: Note[] = new Array();
getNoteList()
的结果但可以将其推送到该变量中以供进一步使用...我希望myVar
拥有Note
的多个对象... = &GT;这些是来自Firebase的JSON,因此是JavaScript对象...... 我该怎么做?
到目前为止,我使用以下内容:
this.noteList .forEach(value => console.log(value));
这会将noteList的每个元素记录为Array [Object]
....
当我this.noteList .forEach(value => this.myVar.push(value));
时,它说:
类型的参数&#39;注意[]&#39;可分配给&#39;注意&#39;类型的参数。财产&#39; id&#39;类型&#39;注意[]&#39;
中缺少
补充类代码是:
export class HomePage {
noteList: Observable<Note[]>
myVar : Note[] = new Array();
constructor(public navCtrl: NavController, private noteListService: NoteListService) {
this.noteList = this.noteListService.getNoteList()
.snapshotChanges()
.map(
changes => {
return changes.map(c => ({
key: c.payload.key, ...c.payload.val()
}))
});
}
this.noteList .forEach(value => this.myVar.push(value));
//Then below, I want to use it in a Jquery
$(function() {
// Also, I don't know how to access neither noteList nor myVar here. Any help here will be appreciated also
}
}
你能帮忙吗?
答案 0 :(得分:3)
使用RxJS执行此操作的正确方法是订阅一个observable并使用subscribe
回调中的结果执行所有必要的操作。如果不重用observable,则不必将其保存到noteList
,但可能需要保存订阅才能取消订阅并避免内存泄漏:
noteListSubscription: Subscription;
constructor(private noteListService: NoteListService) {
this.noteListSubscription = this.noteListService.getNoteList()
.snapshotChanges()
.map(
changes => {
return changes.map(c => ({
key: c.payload.key, ...c.payload.val()
}))
})
.subscribe(notes => { this.myVar = notes });
}
ngOnDestroy() {
noteListSubscription.unsubscribe();
}
应从Subscription
模块导入 rxjs
类型。