我在使用 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
回调。
关于Angular:Observable 在使用管道和选项卡时改变行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64615811/