angular7 - 如何延迟 Angular 7 中错误的 http 响应
问题描述
我正在开发一个 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 毫秒,然后按预期显示结果。但如果响应返回错误,则延迟(1000)函数不工作并且错误块立即工作。我尝试了有无catchError。两者的工作方式完全相同。
解决方案
操作员将仅处理通过“下一个”通知通过可观察对象发送的delay
事件(在您的情况下,这是“成功”)。发生错误时,它会作为“错误”通知发送,并直接跳过您的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);
}
)
}
推荐阅读
- node.js - Angular 2 项目未运行错误 angular/CLI
- python-3.x - Python neo4j 螺栓驱动程序在上下文切换后失去连接
- windows - Ansible Windows ACL
- java - 杰克逊将空值反序列化为空列表,无法访问实体
- mysql - MySql 复杂查询 | 如何从 SELECT 中删除以及如何从数组中创建子列表
- android - recyclerView 中的 android spinner 无法正常工作
- javascript - IE11 WebSocket 对象 onopen:预期对象
- javascript - 如何在 Vue 中对计算属性进行分页
- azure - Umbraco7:在同一个 Azure 存储帐户中设置多个 /media/ blob 容器
- python - 使用 Python Flask/Connexion 和 Swagger 在 API 中处理图像