-1

Here I have an http call which reminds me of an array of "Favorite" objects of size 1 (it is impossible for the call to have more than 1 result). How can I get just the object instead of the array and assign the value to my idFav? (in my code idFav is undefined)

  removeFav(movie:Movie){
   let idFav;
   let idUtente = this.authSrv.getUserId();
   this.http.get<Favorite>(`${this.baseURL}/favorites? 
   userId=${idUtente}&movieId=${movie.id}`).subscribe((val)=>{
   idFav = val;
   console.log(val);  // array of 1 obj
})
   console.log(idFav) // undefined
}

console.log output

R. Richards
  • 24,603
  • 10
  • 64
  • 64
  • Does this answer your question? [How do I return the response from an Observable/http/async call in angular?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular) – R. Richards Sep 18 '22 at 18:38

1 Answers1

0

I'd suggest to use the map operator to convert your response to a desirable one. If you want to get another call based on data you have recieved you can use switchMap operator (use any value form the val object, in example I used userId). For example:

...
this.http.get<Favorite>(`${this.baseURL}/favorites? 
   userId=${idUtente}&movieId=${movie.id}`)
  .pipe(
    map(data => Array.isArray(data) ? data[0] : data),
    switchMap(val => this.http.get(`.../${val.userId}`),
  .subscribe((res)=>{
   //do something with a response from the second request 
});
...
Dmitry S.
  • 1,544
  • 2
  • 13
  • 22
  • really thank you. The problem now is that with "val" i need to make another http call and i guess i can't do that in a subscripe so i really like your answear but how can i resolve now this issude? – Alberto De Maria Sep 18 '22 at 18:50
  • @AlbertoDeMaria, check the corrected solution for the described issue. – Dmitry S. Sep 19 '22 at 14:53