Angular 8 应用程序出错后未调用 Finalize

Sve*_*ger 4 http rxjs angular

我正在尝试在 Angular 8 中构建一个角度应用程序,我从后端获取一个 Observable 并想要订阅它。这是我已经拥有的代码:

this.employeesService.getEmployees$()
      .pipe(
        tap(employees => {
          this.employees = employees;
          console.log(this.employees.length);
        }),
        catchError(err => this.error = err),
        finalize(() => {
          console.log(this.error);
          this.isOperationInProgress = false;
        })
      )
      .subscribe();
Run Code Online (Sandbox Code Playgroud)
this.employeesService.getEmployees$()
Run Code Online (Sandbox Code Playgroud)

这个函数返回一个 Observable,我想用它来做很多事情。

当我尝试到达后端但它处于离线状态时,我没有得到任何函数的返回值。所以这是我的问题:

发生这种情况时,我尝试调用 Finalize 函数。但出现错误后不会调用此函数。

有什么想法如何解决这个问题吗?

And*_*kyi 7

谢谢你的问题。

运算符的官方定义catchError()是:

捕获可观察量上的错误,并通过返回新的可观察量或引发错误来处理。

或者换句话说,该运算符的主要思想是在发生某些错误时返回一个新的可观察值。如果您愿意,我可以提供带有业务逻辑的代码示例。

finalize()操作符的想法是提供在 Observable 完成后启动副作用的可能性。因为错误或者刚刚完成。

因此,如果您想在 BE 服务不可用时显示错误消息,您的代码应该类似于:

this.isOperationInProgress = true;
// I do not recommend the '$' symbol for service methods. But, it's up to you
this.employeesService.getEmployees().pipe(
   tap(console.log),
   finalize(() => this.isOperationInProgress = false)
).subscribe(
    employees => this.employees = employees, 
    error => this.showErrorMesage(error.message)
)
Run Code Online (Sandbox Code Playgroud)

如果您对更详细的解释感兴趣:这是一篇关于错误处理的精彩博客文章。

我希望它有用。我想听听您的任何反馈。祝你今天过得愉快!