I have a firebase database... So it's all JSON. I retrieve the data using AngularFire2 database...I'm reading this tutorial...
The part of the code for this question is :
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() })) });From here I want to do 2 things :
- 1st : declare an array variable outside of the contructor, just like
noteListEx :myVar: Note[] = new Array(); - 2nd : Iterable though the result of the
getNoteList()and push them into that variable for futher use... I hope to havemyVarholding multiple objects ofNote...=> those are JSON from Firebase therefore JavaScript objects...
How do I do that ?
What I've go so far is using the following :
this.noteList .forEach(value => console.log(value)); This will log each element of noteList as Array [Object] ....
When I do this.noteList .forEach(value => this.myVar.push(value)); it says :
Argument of type 'Note[]' is assignable to parameter of type 'Note'. Property 'id' is missing in type 'Note[]'
The comple class code is :
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 }
}Could you guyz help be do this please...
41 Answer
The proper way to do this with RxJS is to subscribe an observable and do all necessary actions with result inside subscribe callback. If the observable isn't reused, it isn't necessary to save it to noteList, but a subscription possibly needs to be saved in order to unsubscribe it and avoid memory leaks:
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 type should be imported from rxjs module.