重构两个订阅吐司消息

时间:2019-02-17 12:51:39

标签: angular rxjs

我有以下代码,我尝试仅通过一个订阅进行重构就没有成功。

this.emailsService.askOptionOne(email).pipe(
  takeUntil(this.ngUnsubscribe)
).subscribe(
  () => {
    this.isBusy = false;

    assistanceForm.reset();
    this.router.navigate(['/']);

    this.translateService.get('The request has been sent.').subscribe((message: string) => {
      this.toastrService.success(message);
    });
  },
  (error: any) => {
    this.isBusy = false;

    this.translateService.get(error).subscribe((message: string) => {
      this.toastrService.error(message);
    });
  }
);

到目前为止我尝试过的事情:

this.emailsService.askOptionOne(email).pipe(
  switchMap(() => of('The request has been sent.')),
  catchError((error: any) => of(error)),
  switchMap((message: any) => this.translateService.get(message)),
  takeUntil(this.ngUnsubscribe)
).subscribe(
  (message: any) => {
    this.isBusy = false;

    assistanceForm.reset();
    this.router.navigate(['/']);

    this.toastrService.success(message);
  },
  (error: any) => {
    this.isBusy = false;

    this.toastrService.error(error)
  }
);

此版本的问题是结果永远不会出错。

有任何线索可以重构此代码吗?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

要进入subscribe中的错误回调,您必须抛出一个错误。

我认为这应该可行:

this.emailsService.askOptionOne(email).pipe(
  tap(() => this.isBusy = false),
  switchMap(() => this.translateService.get('The request has been sent.')),
  catchError(error => this.translateService.get(error).pipe(
    map(message => throw new Error(message))
  )),
  takeUntil(this.ngUnsubscribe)
).subscribe(
  message => {
    assistanceForm.reset();
    this.router.navigate(['/']);
    this.toastrService.success(message);
  },
  (error: any) => this.toastrService.error(error.message)
);