我的组件上有这个代码
this.authService.login4(this.email, this.password)
.pipe(first())
.subscribe(
data => {
console.log(data);
},
error => {
console.log('err');
});
Run Code Online (Sandbox Code Playgroud)
我的服务上的这个实现:
login4(email: string, password: string): Observable<any> {
return this.http.post('http://localhost:3000/api' + '/login', {
email: email,
password: password
});
}
Run Code Online (Sandbox Code Playgroud)
并且在出现错误时会打印 err,但是如果我将 login 的实现更改为此,则不会打印组件 err。这是正常的吗?我想知道组件中是否有任何错误。
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`))
);
}
Run Code Online (Sandbox Code Playgroud)
如果你发现一个错误,你就会停止它。您可以捕获并抛出,或者在到达组件之前不捕获。请参阅以下两个示例:
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");
})
);
}
Run Code Online (Sandbox Code Playgroud)
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)
);
}
Run Code Online (Sandbox Code Playgroud)
两者都会起作用。
| 归档时间: |
|
| 查看次数: |
3690 次 |
| 最近记录: |