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`);
});
NOTE: The trailing
$ontrimlines$is a convention to indicate that a variable holds an observable, otherwise known as an event $tream.
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 in dropdown. 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 button should 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 async pipe 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>
NOTE: Unless you use
.subscribe()or theasyncpipe, the observable will not retrieve results. That's another advantage over promises: the request doesn't start until you subscribe to it.
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.