tom*_*nes 6 observable rxjs typescript angular
我有一个 firebase 数据库......所以它都是 JSON。我使用 AngularFire2 数据库检索数据...我正在阅读本教程...
这个问题的代码部分是:
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()
}))
});
Run Code Online (Sandbox Code Playgroud)
从这里我想做两件事:
noteListEx一样:myVar: Note[] = new Array();getNoteList()并将它们推入该变量以供进一步使用......我希望拥有......的myVar多个对象Note=>那些是来自Firebase的JSON,因此JavaScript对象......我怎么做 ?
到目前为止,我使用的是以下内容:
this.noteList .forEach(value => console.log(value));这会将 noteList 的每个元素记录为Array [Object]....
当我这样做this.noteList .forEach(value => this.myVar.push(value));时说:
“Note[]”类型的参数可分配给“Note”类型的参数。“Note[]”类型中缺少属性“id”
完整的类代码是:
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
}
}
Run Code Online (Sandbox Code Playgroud)
你能帮我做这件事吗...
使用 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();
}
Run Code Online (Sandbox Code Playgroud)
Subscription类型应该从rxjs模块导入。
| 归档时间: |
|
| 查看次数: |
16679 次 |
| 最近记录: |