Angular 7: How to re-write nested subscribtions?

会有一股神秘感。 提交于 2019-12-20 06:12:25

问题


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.

  1. 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.

  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!