RxJS 订阅内部订阅错误操作 [英] RxJS subscribe inside subscribe with actions on error

查看:52
本文介绍了RxJS 订阅内部订阅错误操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 subscribe 中有带有 subscribe 的代码:

I have code with subscribe inside subscribe:

this.http.post('/update1', newData).subscribe(
    (response) => {
        const r = response.json;
        const id = r['id'];
        this.http.post('/update2?id=' + id, newData).subscribe(
            () => {
                this.http.post('/update3?id=' + id, newData).subscribe(
                    () => {
                        console.log('success');
                    },
                    () => {
                        // revert changes made to update2
                        this.http.post('/update2', previousValues).subscribe();
                        // revert changes made to update1
                        this.http.post('/update1', previousValues).subscribe();
                    });
            },
            () => {
                // revert changes made to update1
                this.http.post('/update1', previousValues).subscribe();
            }
        );
    },
    (error) => {
        console.log(error);
    }
);

如何在 RxJS 5 中优化它?

How can I optimize it in RxJS 5?

推荐答案

请不要在另一个订阅中使用订阅. 使用原生 RxJS 运算符,有更好的方法来解决这个问题:

Please don't use subscribe inside another subscribe. Using native RxJS operators, there is better way around this which will be:

this.http
  .post('/update1', newData)
  .pipe(
    map((response) => response.json),
    map((data) => data.id),
    switchMap((id) =>
      this.http.post('/update2?id=' + id, newData).pipe(
        switchMap(() => this.http.post('/update3?id=' + id, newData)),
        catchError((err) => {
          // this catcherror will happen if update3 failes
          return merge(
            // revert changes made to update2
            this.http.post('/update2', previousValues),
            // revert changes made to update1
            this.http.post('/update1', previousValues),
          );
        }),
      ),
    ),
    catchError((err) => {
      // this catcherror will happen if update2 failes
      // revert changes made to update1
      return this.http.post('/update1', previousValues);
    }),
  )
  .subscribe(
    (result) => {
      console.log(result);
    },
    (err) => {
      // this error will happen if an error happens wich is not caught
      console.log(err);
    },
  );

这样,如果您愿意,您只有一种订阅方法来处理最后剩余的结果.

This way you only have one subscribe method to handle last remaining result if you want to.

请记住,如果在任何地方之前触发异常,则管道内的 catchError() 将被触发.如果异常已经被处理程序处理了,同样的异常不会触发其他 catchError() 两次.

Keep in mind that catchError() inside pipe will be trigerred if exception is fired prior to it anywhere. If exception is handled already, by the handler, same exact exception will not trigger other catchError() twice.

这篇关于RxJS 订阅内部订阅错误操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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