[SOLVED] It’s ok to make an http call in an observable or it’s better something else?


This Content is from Stack Overflow. Question asked by Alberto De Maria

I made an http call inside an observable, do you think it is okay or should I split the two?




This is not recommended to call an observable inside another’s subscribe block. What you could do here is the following:

removeFav(movie: Movie) {
  return this.getFavIdByMovie(movie).pipe(
    switchMap((data) => this.http.delete(`${this.baseURL}/favorites/${data[0].id}`)

Here, you are converting one stream into another through the use of switchMap operator. So you will have to subscribe to the removeFave(movie) stream to actually delete it (because unless you subscribe, it is in a cold state). An example usage:

onClickDelete() {
    next: () => this.showAlert('Deleted');

Second part
To unwrap a single object from the array of objects, you can use a map operator from RxJS.

getFavIdByMovie(movie: Movie): Observable<Favorite> {
  let userId = this.authService.getUserId();
  return this.http
       map((results) => results?.[0])

Now, you will get a single object instead of an array.

This Question was asked in StackOverflow by Alberto De Maria and Answered by Touhid Rahman It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?