[英]Angular POST request not passing result back after rxjs catchError()
I am trying to catch errors in a POST method using catchError.我正在尝试使用 catchError 在 POST 方法中捕获错误。 However when I get an invalid response (eg the login fails) the code executes the catchError() (the console.log is printed), but I never see the console message "login result received" from the subscription.但是,当我收到无效响应(例如登录失败)时,代码会执行 catchError() (打印 console.log),但我从未看到来自订阅的控制台消息“已收到登录结果”。 Why isn't catchError passing a value back to the subscription?为什么 catchError 不将值传递回订阅? Note that everything works as expected when the login succeeds (the console.log is printed correctly)请注意,当登录成功时,一切都按预期工作(console.log 打印正确)
this.auth.login(this.model.username, this.model.password).subscribe(x=>{
console.log('login result received');
this.loading=false });
my service:我的服务:
login(username: string, password: string): Observable<boolean> {
return this.http.post<TokenResponse>('/api/auth/token', { name: username, password: password }).pipe(
catchError(this.appSvc.handleError<boolean>("auth/login", false)),
map((response: TokenResponse) => {
if (response !=null) {
// do token things
return true;
}
else
alert('rxjs token null')
}
));
}
public handleError<T>(operation = 'operation', result?: T){
console.log('got here');
return of(result as T);}
You are using the catchError
in the pipe incorrectly.您在管道中错误地使用了catchError
。 Should be:应该:
catchError(error => this.appSvc.handleError<boolean>("auth/login", false))
See also the Stackblitz with working code here: https://stackblitz.com/edit/angular-hugqem另请参阅此处包含工作代码的 Stackblitz: https ://stackblitz.com/edit/angular-hugqem
It turns out that the result from catchError (a boolean) was being passed to map because the catchError was firing, then map was attempting to map the result.结果是 catchError (布尔值)的结果被传递给 map 因为 catchError 被触发,然后 map 试图映射结果。 In my case就我而言
My fix was:我的解决方法是:
Full code:完整代码:
login(username: string, password: string): Observable<boolean> {
return this.http.post<TokenResponse>('/api/auth/token', { name: username, password: password }).pipe(
catchError(this.appSvc.handleError<boolean>("auth/login", false)),
map((response: any) => {
if (response.token !=null) {
// do token things
return true;
}
else if (typeof response==="boolean") //note that catcherror will pass its return type (bool) to here
return false
else
alert('rxjs token null')
}
));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.