angular - 在 rxjs catchError() 之后,角度 POST 请求未将结果传回
问题描述
我正在尝试使用 catchError 捕获 POST 方法中的错误。但是,当我收到无效响应(例如登录失败)时,代码会执行 catchError()(打印 console.log),但我从未从订阅中看到控制台消息“收到登录结果”。为什么 catchError 不将值传递回订阅?请注意,登录成功后一切正常(console.log 打印正确)
this.auth.login(this.model.username, this.model.password).subscribe(x=>{
console.log('login result received');
this.loading=false });
我的服务:
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);}
解决方案
您catchError
在管道中使用不正确。应该:
catchError(error => this.appSvc.handleError<boolean>("auth/login", false))
另请参阅此处的 Stackblitz 和工作代码:https ://stackblitz.com/edit/angular-hugqem
推荐阅读
- c# - 添加到委托的附加信息
- pandas - 识别差异的最佳方法:欧几里得距离、余弦距离还是简单减法?
- apache-nifi - 如何在 getMongo 处理器中参数化 URI
- android - 两台安卓设备离线连接
- css - 菱形网格图像的 MAC OS 问题
- ruby-on-rails - Debug / Execute Discourse plugin from command line
- docker - Docker - ulimit differences between container and host
- python - Remove repeated header lines from a txt file but keep the first header row
- java - 从 ImageResource 中的字符串设置图像
- kubernetes - 节点冻结排水