angular 4-如何重写嵌套订阅 [英] angular 4 - How to rewrite nested subscription

查看:80
本文介绍了angular 4-如何重写嵌套订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套订阅,我认为这不是一个好习惯,尽管它通常对我有用,但在某些情况下可能会给我带来麻烦.

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);
                        });
                    }
                });

推荐答案

我始终建议人们尽力将 logic 保留在自己的信息流中,并将 effects 保留在订阅中或.do()回调.因此,我认为您避免嵌套订阅的本能是正确的.

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 );
    });

如果您发现自己想避免嵌套订阅,那么通常您想联系*Map运算符之一.

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

rxjs中,有四个

  1. mergeMap
  2. concatMap
  3. switchMap
  4. exhaustMap
  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 4-如何重写嵌套订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆