问题
I have a component that displays a filtered list of items. It is subscribed to two observables - the first one is for (filter) parameters that need to be passed into the second observable to get the filtered list of items.
public filteredItems = [];
this.myService.getFilterParams()
.subscribe(params => {
this.myService.getFilteredItems(params)
.subscribe(items => { this.filteredItems = items});
});
I've read that chaining subscribtion is not the best practice (the code works fine otherwise), so how can I re-write it?
回答1:
You can use either mergeMap
or switchMap
to achieve this. Difference is that switchMap
will cancel inner subscription if outer subscription emits new values, mergeMap
won't.
this.myService
.getFilterParams()
.pipe(mergeMap(params => this.myService.getFilteredItems(params)))
.subscribe(items => {
this.filteredItems = items;
});
回答2:
You can use switchMap, mergeMap, concatMap higher order operators here.
Use mergeMap if your first observable will emit multiple values and you want to collect responses from all the inner observables in the subscribe function. Also it will send the requests in parallel and the order will not be maintained when getting response in subscribe.
You can also use concatMap which will send the first request collect the response and then send the second request for your inner observable.
Looking at your code i suggest to use switchMap which will cancel any new values are emitted from your first observable and only last inner observable value is received in your subscribe.
Also tap the response to do any intermediate steps if needed.
Hope this helps.
this.myService
.getFilterParams()
.pipe(
tap( (res) => {
// do any intermediate steps
console.log(res);
}),
switchMap(params => this.myService.getFilteredItems(params))
)
.subscribe(items => {
this.filteredItems = items;
});
来源:https://stackoverflow.com/questions/57562159/angular-7-how-to-re-write-nested-subscribtions