Angular 2 - HTTP request chains

I get the RxJS Observable from httpService, which is the actual http from Angular. Now, as soon as I get a positive result from this, I want to process the next http request that I receive from this.retrieve() . These are more or less concattening requests. Is there a better way to do this?

 return this.httpService.query(data) .map(data => { if(data.status > 1) this.retrieve().subscribe(); return data; }); 
+6
source share
1 answer

HTTP request chains can be reached using the Observable.flatMap statement. Suppose we want to make three queries, each of which depends on the result of the previous one:

 this.service.firstMethod() .flatMap(firstMethodResult => this.service.secondMethod(firstMethodResult)) .flatMap(secondMethodResult => this.service.thirdMethod(secondMethodResult)) .subscribe(thirdMethodResult => { console.log(thirdMethodResult); }); 

This way you can link as many interdependent queries that you want.

+12
source

Source: https://habr.com/ru/post/1015523/


All Articles