首页 > 解决方案 > 在 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);}

标签: angularpostrxjs

解决方案


catchError在管道中使用不正确。应该:

catchError(error => this.appSvc.handleError<boolean>("auth/login", false))

另请参阅此处的 Stackblitz 和工作代码:https ://stackblitz.com/edit/angular-hugqem


推荐阅读