【问题标题】:RxJs not switchMap if an error occured in the top level subscription如果顶级订阅发生错误,RxJs 不会 switchMap
【发布时间】:2021-10-25 09:23:32
【问题描述】:

如果我的第一个 Observable 抛出错误,那么我就不会订阅我的 switchMap observable。

这可能吗?

this._profileService.updateProfile(profile).pipe(
  tap(profile => {
    this.profile = profile;
    this.saving = false;
    this.updateForm(this.profile);
  }),
  catchError(error => {
    console.log(error);
    this.saving = false;
    this.updateForm();
    return this._pjNotificationService.show(PjNotificationType.ERROR, 'Fehler beim Speichern',
      `Beim Speichern ist ein Fehler aufgetreten. ${error}`, 15000)
  }),
  switchMap(() => this._pjNotificationService.show(PjNotificationType.SAVED, 'Änderungen gespeichert', '', 15000))
).subscribe();

【问题讨论】:

    标签: javascript angular typescript rxjs observable


    【解决方案1】:

    由于您的运算符的顺序,catchError 返回的 observable 将继续到 switchMap

    您可以更改运算符的顺序,使switchMap 位于catchError 之前:

    this._profileService.updateProfile(profile).pipe(
      tap(profile => {
        this.profile = profile;
        this.saving = false;
        this.updateForm(this.profile);
      }),
      switchMap(() => this._pjNotificationService.show(PjNotificationType.SAVED, 'Änderungen gespeichert', '', 15000)),
      catchError(error => {
        console.log(error);
        this.saving = false;
        this.updateForm();
        return this._pjNotificationService.show(PjNotificationType.ERROR, 'Fehler beim Speichern',
          `Beim Speichern ist ein Fehler aufgetreten. ${error}`, 15000)
      })
    ).subscribe();
    

    这样,如果this._profileService.updateProfile(profile) 抛出错误,switchMap 将被跳过,因为它会跳转到catchError

    【讨论】:

    • 哦,坦克,它的工作。我想如果我在 catchError 之前 switchMap 我只会捕获第二个 Observable 的错误。
    • 您在catchError 之前捕获每个操作员的所有错误:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    相关资源
    最近更新 更多