【问题标题】:Is there a chance to omit 'next' part from RxJs 'subscribe'是否有机会从 RxJs 'subscribe' 中省略 'next' 部分
【发布时间】:2020-01-23 21:36:48
【问题描述】:

我想知道是否可以将以下代码转换为没有来自 RxJS“订阅”的“下一个”部分的代码。我对从服务中获得任何结果不感兴趣。唯一重要的是捕捉潜在错误以做出正确反应。

    this.someService.getSomething(this.id)
      .pipe(
          takeUntil(this.destroy$)
      )
      .subscribe(() => {
        // I don't need this part at all
      }, (error: HttpErrorResponse) => {
        if (error.status === 404) {
           // doing sth important
        }
      });

有没有机会在 Angular 中做点什么?

【问题讨论】:

    标签: javascript angular rxjs observable refactoring


    【解决方案1】:

    你可以试试catch / catchError:

    DEMO

    this.someService.getSomething(this.id)
      .pipe(
        takeUntil(this.destroy$),
        catchError(
          (error: HttpErrorResponse) => {
            if (error.status === 404) {
              // doing sth important
            }
          })
      );
    

    【讨论】:

      【解决方案2】:

      如上所述,您可以使用catchError 运算符。但是,如果你仍然需要订阅,你也可以使用像这样的订阅方法this.someService.getSomething(this.id).subscribe(null, (error) => {..})

      【讨论】:

        【解决方案3】:

        您可以传递PartialObserver 来订阅并定义或省略nexterrorcomplete

        source.subscribe({ error: (e: any) => console.error(e) })
        

        【讨论】:

          猜你喜欢
          • 2020-09-14
          • 2018-03-24
          • 1970-01-01
          • 2017-03-03
          • 1970-01-01
          • 1970-01-01
          • 2020-11-21
          • 2020-06-20
          • 1970-01-01
          相关资源
          最近更新 更多