此外,在移除分接管道时,会按预期调用完成处理程序。
我正在使用Angular 10,遇到了一个问题,即我的可观察到的完成行为会发生变化,这取决于我是否使用管道。以下是我的代码的两个相关部分。
身份验证服务.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');
}
})
);
}
...
身份验证组件.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
回调。