angular 4 - How to rewrite nested subscription

2020-07-26 14:26发布

问题:

I have a nested subscription which I believe is not good practice, and even though it usually works for me, in one instance it might causing me a problem.

How could I rewrite the following so it is not nested subscription?

this.pagesService.postReorderPages(ids).subscribe(res => {
                    if (res === "ok") {
                        console.log(res);
                        this.pagesService.getPages().subscribe(pages => {
                            this.pagesService.pagesBS.next(pages);
                            console.log(pages);
                        });
                    }
                });

回答1:

I always recommend that people do their best to keep logic in their stream, and effects inside subscriptions or .do() callbacks. So i think your instincts about avoiding nested subscriptions are on point.

this.pagesService.postReorderPages( ids )
    .filter( res => res === 'ok' ) // moved logic from your subscription to stream
    .mergeMap( () => this.pagesService.getPages() )
    .subscribe( pages => {
        this.pagesService.pagesBS( pages );
    });

If you find yourself trying to avoid a nested subscription, oftentimes you want to reach for one of the *Map operators.

In rxjs, there are four of these

  1. mergeMap
  2. concatMap
  3. switchMap
  4. exhaustMap

They all behave a little differently, so I can't guarantee that this will implement your feature perfectly. But they all have the same signature, and they exist to handle "messy" nested subscribes (also sometimes referred to as "higher-order" or "meta" streams, in some libraries).



标签: angular