Angular:Observable 在使用管道和制表符时改变了行为

Angular: Observable changes behavior when using a pipe and tab

我正在使用 Angular 10 并遇到一个问题,即我的可观察对象的完成行为会发生变化,这取决于我是否使用管道。这是我的代码的两个相关部分。

auth.service.ts

...
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
...
register(email: string, password: string): Observable<RegistrationResponse> {
    return this.http.post<RegistrationResponse>(
      `${environment.API_URL}/users/register`,
      { email, password }).pipe(tap<RegistrationResponse>({
        next: (data) => {
          console.log('success - tap');
          if (data.jwt !== undefined) {
            this.setSession(data.jwt);
          }
        },
        error: () => {
          console.log('error - tap');
        }
      })
    );
}
...

auth.component.ts

...
this.authService.register(this.email, this.password).subscribe({
    next: (_) => {
      console.log('success');
      this.router.navigate(['/']);
    },
    error: (error) => {
      console.log('error');
      this.error = error.error || 'Error';
      this.loading = false;
    }
});
...

当请求失败并且我收到错误响应时,它会导致以下输出(如预期):

error - tap
error

但是当请求成功时,我得到这个:

success - tap
error                 <--- unexpected

=> 这有什么意义,我错过了什么?


此外,在移除自来水管时,会按预期调用完成处理程序。
register(email: string, password: string): Observable<RegistrationResponse> {
    return this.http.post<RegistrationResponse>(
      `${environment.API_URL}/users/register`,
      { email, password })/*.pipe(tap<RegistrationResponse>({
        next: (data) => {
          console.log('success - tap');
          if (data.jwt !== undefined) {
            this.setSession(data.jwt);
          }
        },
        error: () => {
          console.log('error - tap');
        }
      })
    );*/
}

输出:

success

您的 tap next 回调中的某些代码可能会引发错误(检查 this.setSession(data.jwt))。运算符中抛出的错误被 RxJS 捕获并作为错误通知发送。因此,如果 pipe 上游发生错误,subscribe 中的 error 回调将被调用。