I have problem with my Observable in my service. I need to fetch data for 3 players. My subscription sign data from service to local variable and push it into array. Fine, but when i return data from if statement i have bug. I can see only one of 3 players. How can i store all data for whole life time of my app? Regards.
Service:
getData(query): Observable<any> {
if(this.dataFromDb)
{
return Observable.of(this.dataFromDb);
}
return this.http.get(query)
.map(res => res.json())
.do(res => this.dataFromDb = res)
.catch(err => Observable.throw(err.json() || 'Błąd');
}
}
Component:
export class FriendsComponent implements OnInit {
myDataFromDb: any[] = [];
constructor(public dataService: DataService) {
}
private getDataFromDb(query) {
this.dataService.getData(query).subscribe((data) =>
{
this.myDataFromDb.push(data);
console.log(data);
});
}
ngOnInit() {
for (let i of this.dataService.friends) {
this.dataService.query = `${this.dataService.apiUrl}${i.nick}${this.dataService.apikey}`;
this.getDataFromDb(this.dataService.query);
}
console.log(this.myDataFromDb);
}
}