Home > Net >  Return asynchronous data from an angular method
Return asynchronous data from an angular method

Time:02-12

I am fairly new to angular and am still trying to wrap my head around doing things the angular httpClient rxjs way. I am trying to write the rxjs equivalent of the following:


async onButtonClick = () => {
    const processedBooks = await this.getAndProcessBooks();
    await myGenericHttpClient.post('/api/something', processedBooks);
}

async getAndProcessBooks = () => {
    const books = await myGenericHttpClient.get('/api/books');

    const processedBooks = books.map(book => {
        return book.read = true;
    });

    return books;
};


My understanding of rxjs is i need to use angular's httpClient to make the request then subscribe to the response:

getAndProcessBooks = () => {
    return httpClient.get('/api/books').subscribe(books => {
        return books;
    });
};

However, the problem is getAndProcessBooks returns a subscription, not an array of books so I'm not sure how this method can return the data that I need. Any help or direction to resources would be appreciated!

CodePudding user response:

You can take the result from one API call and send it to another API call using the different map operators such as mergeMap, concatMap, etc of RxJs, which ever suits your use case.

I separated your HTTP calls and created functions for them just for easy readability.

//Returns Books
getAndProcessBooks(): Observable<any> {
    return this.myGenericHttpClient.get('/api/books');
}

//API something that requires books to send call
apiSomethingFunction(processedBooks: any): Observable<any> {
   return this.myGenericHttpClient.post('/api/something', processedBooks);
}

//On the button click
 onButtonClick(): void {
    this.getAndProcessBooks()
      .pipe(
        switchMap((books) => {
          //Response of books comes here, you can map them before sending it to the something API
          return this.apiSomethingFunction(books);
        })
      )
      .subscribe((resp) => {
        console.log(resp);
        console.log('I got Response of API Something');
      });
  }

The reason I used switchMap operator was to cancel the previous HTTP call if the user clicks on the button again. You can use different map if your use-case is different.

CodePudding user response:

You could just take the observable and use it directly.

unprocessedBooks$: Observable<any>;

getAndProcessBooks() {
    unprocessedBooks$ = httpClient.get('/api/books').pipe(data => {return data;});
};

And in html

<div>{{ unprocessedBooks$ | async}}</div>
  • Related