angular - Angular Observer 在组件上捕获错误
问题描述
我的组件上有这个代码
this.authService.login4(this.email, this.password)
.pipe(first())
.subscribe(
data => {
console.log(data);
},
error => {
console.log('err');
});
以及我的服务上的这个实现:
login4(email: string, password: string): Observable<any> {
return this.http.post('http://localhost:3000/api' + '/login', {
email: email,
password: password
});
}
如果出现错误,则会打印错误,但是如果我将登录的实现更改为此,则不会打印组件错误。这是正常的吗?我想知道组件中是否有任何错误。
login4(email: string, password: string): Observable<any> {
return this.http.post('http://localhost:3000/api' + '/login', {
email: email,
password: password
}).pipe(
tap(data => console.log(data)),
catchError(this.handleError<any>(`err`))
);
}
解决方案
如果您发现错误,您将停止它。您可以接住并扔掉,也可以在它到达组件之前不接住。请参见下面的两个示例:
接住并扔掉。对于处理预期的错误很有用。
ngOnInit() {
this.login().subscribe(
res => {
console.log(res);
},
err => {
console.log(err);
}
);
}
login() {
return ajax.post("http://localhost:3000/api/login").pipe(
map(data => data),
catchError(err => {
throw new Error("My Error");
})
);
}
直到在组件中才捕获。
ngOnInit() {
this.login().subscribe(
res => {
console.log(res);
},
err => {
console.log(err);
}
);
}
login() {
return ajax.post("http://localhost:3000/api/login").pipe(
map(data => data)
);
}
两者都会起作用。
推荐阅读
- python - 如果使用 python 卡住,请尝试干净重启和超时
- java - TreeSet_获取对象的值而不是期望的实例变量值
- flutter - 我需要处置cubit实例吗?
- javascript - React native cameraWithTensors onReady 仅在保存文件时调用
- c# - 如何从另一个 ListView 绑定 ListView 中的对象属性
- python - python:如何监控变量?变量变化时执行命令
- xamarin.forms - 未找到“HeightRequest”的属性、BindableProperty 或事件,或者 Xamarin.Forms 中的值和属性错误之间的类型不匹配
- javascript - 模拟默认导出失败,但命名导出没有
- flutter - 颤振发送带有 url_launcher uri 的电子邮件
- javascript - Puppeteer .click 悬停而不是单击