Search code examples
angulartypescripthttprequest

HTTP Call return an array of 1 object. How can i get just the object and assign value to the var? Angular / TS


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


Solution

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