我有一个 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()
}))
});
从这里我想做两件事:
- 1st : 在构造函数之外声明一个数组变量,就像
noteList
Ex :myVar: Note[] = new Array();
- 第二:可迭代
getNoteList()
的结果并将它们插入该变量以供进一步使用...我希望myVar
持有的多个对象code>Note
...=> 这些是来自 Firebase 的 JSON,因此是 JavaScript 对象...
我该怎么做?
到目前为止,我使用的是以下内容:
this.noteList .forEach(value => console.log(value));
这会将 noteList 的每个元素记录为 Array [Object]
....
当我执行 this.noteList .forEach(value => this.myVar.push(value));
时,它说:
Argument of type 'Note[]' is assignable to parameter of type 'Note'. Property 'id' is missing in type 'Note[]'
完整的类代码是:
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
}
}
请你们帮忙做这件事...
最佳答案
使用 RxJS 执行此操作的正确方法是订阅一个可观察对象,并在 subscribe
回调中执行所有必要的操作并返回结果。如果不重用可观察对象,则无需将其保存到 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();
}
订阅
类型应该从rxjs
模块导入。
关于angular - 循环遍历 Typescript 中的 observable<Object[ ]>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50089583/