我正在开发一个Angular7项目,并且在http请求上有一些关于错误处理的问题。
这是我的登录组件,有两个功能
export class LoginComponent implements OnInit, OnDestroy {
emailLogin1() {
this.authService.emailLogin1(this.loginForm.value).pipe(delay(1000)).subscribe(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
);
}
emailLogin2() {
this.authService.emailLogin2(this.loginForm.value).pipe(delay(1000)).subscribe(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
);
}
}
这是我的AuthService有两个功能。
export class AuthService {
constructor(private http: HttpClient) {
}
emailLogin1(values): any {
return this.http.post(environment.server + '/auth/emailLogin', values).pipe(
tap(
(response) => {
localStorage.setItem('token', response['token']);
},
(error) => {
console.log(error);
}
)
);
}
emailLogin2(values): any {
return this.http.post(environment.server + '/auth/emailLogin', values).pipe(
tap(
(response) => {
localStorage.setItem('token', response['token']);
}
),
catchError((error) => {
console.log(error);
throw error;
})
);
}
}
当我向服务器发出请求时,如果响应状态成功,则等待1000毫秒,然后按预期显示结果。但是如果响应返回错误,则delay(1000)功能不起作用,并且错误阻止立即工作。我尝试使用和不使用catchError。两者的工作方式完全相同。
delay
运算符仅适用于通过“next”通知通过observable发送的事件(在您的情况下,这是“成功”)。发生错误时,它会作为“错误”通知发送,并且会跳过您的delay
操作员。如果你想延迟错误,你应该抓住它,引入延迟,然后重新抛出它:
emailLogin1() {
this.authService.emailLogin1(this.loginForm.value).pipe(
delay(1000), // only affects "success"
catchError(error => interval(1000).pipe( // only affects "error"
mergeMap(() => throwError(error)) // re-throw error after our delay
)),
).subscribe(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
)
}