【发布时间】:2018-10-09 21:41:21
【问题描述】:
我有一个 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例如:myVar: Note[] = new Array(); - 2nd :虽然
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
}
}
你能帮我做这件事吗...
【问题讨论】:
-
问题可能是XY问题。您正在尝试将现代方法(这是 Angular+Ionic,不是吗?)与老式的“jQuery 编程”相结合。永远不应该这样做。由于多种原因,jQuery 在 Angular 应用程序中是绝对禁忌的。关于 Then below 和 我不知道如何在此处访问 noteList 和 myVar,这是 stackoverflow.com/questions/14220321/… 的欺骗。您需要接受 observables,而不是为您可能更熟悉的 jQuery 创建桥梁。您可以访问 observable
.subscribe中的值 -
@estus 哦,告诉我...编程已经走了很长一段路,我知道我需要更新我的技能...我会考虑您对 jquery 的建议...但是对于
.subscribe部分,您的任何提醒将不胜感激....我将如何迭代.subscribe结果以允许我使用Array.push方法构造myVar? -
你不需要迭代它。这是
.subscribe(notes => { this.myVar = notes }) -
@estus 谢谢你,伙计......它工作......如果你想投票给我的OP,你可以添加它作为答案;-)
标签: angular typescript rxjs observable