1
votes

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);
    }
}

And some photo of problem: Data on start Data on start

Data after route change. Data after route change

1

1 Answers

2
votes

You must use a object to "cache" the response. Personally I'll choose send to my function the nick and the apiKey, but as you send query, you can do

dataFromDb:any={};
getData(query): Observable<any> {
if(this.dataFromDb[query])
{
  return Observable.of(this.dataFromDb[query]);
}

    return this.http.get(query)
      .map(res => res.json())
      .do(res => this.dataFromDb[query] = res)
      .catch(err => Observable.throw(err.json() || 'Błąd');
  }
}