Again, I think your problem isn't framework specific (Angular vs. other frameworks). Basically, it is async programming. There are multiple way to handle the scenario. You can use callbacks, promises, or the new async await model also.
I don’t know the angular http client but on angularJS or with separate promises based libs like axios you’d just chain the calls. The angular docs are not quite clear, but it looks like the pipe command is doing some similar thing.
$http.get(„“).then(response => $http.get(„“)).then(response2 => ...)
Moses M
Frontend Engineer
Matt Strom
Software Engineer, TypeScript ninja
Using RxJS is the preferred approach in Angular (and an incredibly powerful one).
Example:
const trimlines$ = Observable.fromEvent(button, 'click') .mapTo(dropdown.value) .switchMap((make) => { return this.http.get(`cars/${make}/models`) .map((models) => models[rand]); }) .switchMap((model) => { return this.http.get(`cars/${model}/trimlines`); });What's happening here is that I've wired up a click handler onto
button. When the button is clicked, a call goes out to retrieve the list of car models from the manufacturer selected indropdown. When that list returns, a random model is chosen and then a second call goes out to retrieve the trimlines for that model.One advantage with using observables here is that, unlike promises, observables are cancelable. Therefore, in the example above, if
buttonshould be clicked again before the first request returns (or even the second), the request is dropped and a new one is started.switchMap()is one of the Rx operators that enables an event stream to be cancelled.In Angular you can also use the
asyncpipe in your HTML markup to use an observable value and refresh when the observable changes. Example:<ul> <li *ngFor="let trim of trimlines$ | async"> {{ trim }} </li> </ul>RxJS does even more powerful things than that. For example, you could add the ability for the code to retry each request 3 times if a previous request fails simply by using the
retry()operator. Example:.switchMap((make) => { return this.http.get(`cars/${make}/models`) .retry(3) .map((models) => models[rand]); }) .switchMap((model) => { return this.http.get(`cars/${model}/trimlines`) .retry(3); });If you don't already know RxJS, it's worth the time to learn. The learning curve can be steep, but the library is incredibly powerful and very rewarding to use.