【问题标题】:Angular - pipe function break execution flowAngular - 管道函数中断执行流程
【发布时间】:2021-10-19 08:51:30
【问题描述】:

我有以下代码:

 subscriber.pipe(
       switchMap(data => {
          this.getData().pipe(
             map(() => res),
             catchError(error => {
                 return of(null);
             })
          );
       }),
       switchMap(data => {
    
       })
    
    ).subscribe();

如果第一个 switchMap 出现错误,我将返回 of(null),因此下一个 switchMap 会将数据接收为 null。 但是我喜欢停止执行,以防第一个 switchMap 进入 catchError 块,它不应该执行第二个 switchMap。有没有办法做到这一点?

【问题讨论】:

  • 没有发现错误?
  • 我还需要在代码 sn-p 中显示我错过的错误消息,我像 Tobias 建议的那样在末尾添加了 catchError 块。
  • 在您没有使用error 的示例中,请注意,如果您在catchError 中确实有事情要做,但希望整体结果保持不变,您也可以使用throwError

标签: angular typescript rxjs rxjs-observables


【解决方案1】:

RxJS #空

EMPTY 是一个不发射任何内容并立即完成的可观察对象。

subscriber.pipe(
       switchMap(data => {
          this.getData().pipe(
             map(() => res),
             catchError(_ => EMPTY)
          );
       }),
       switchMap(data => {
    
       })
    
    ).subscribe();

【讨论】:

    【解决方案2】:

    我认为你可以在这里使用过滤器。从 catch 错误你可以返回 null 并且在第一个 switchMap 之后你可以使用过滤器来过滤掉 null。

    subscriber.pipe(
           switchMap(data => {
              this.getData().pipe(
                 map(() => res),
                 catchError(error => {
                     return null;
                 })
              );
           }),
           filter(v => v),
           switchMap(data => {
        
           })
        
        ).subscribe();
    

    【讨论】:

      【解决方案3】:

      catchError 放在管道的末尾。

      subscriber.pipe(
         switchMap(data => {
             ...
         }),
         switchMap(data => {
             ...
         }),
         catchError(error => {
             return of(null);
         })
      ).subscribe(val => {
          // val will be null if any error happened
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-27
        • 1970-01-01
        • 2016-04-21
        • 2021-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-02
        相关资源
        最近更新 更多