1

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 Answer 1

2

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');
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Huge mug of beer for this man! Many people tried to help me but your answer was correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.