角度捕获 HTTP 异常

  • 本文关键字:HTTP 异常 angular
  • 更新时间 :
  • 英文 :


所以我试图在用户输入无效的用户名密码组合时显示错误消息。

我的用户服务:

  login(accountCredentials: AccountCredentials): Observable<boolean> {
return this.http.post(UrlHelper.routeTo("auth/login"), JSON.stringify(accountCredentials))
  .map(n => {
    this.authService.setToken(n.json().token);
    this.globalEventsManager.login.emit();
    return true;
  });}

我的http.service:

  request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
let token = this.authService.getEncodedToken();
if (typeof url === 'string') { // meaning we have to add the token to the options, not in url
  if (!options) {
    // let's make option object
    options = {headers: new Headers()};
  }
  options.headers.set('Authorization', `Bearer ${token}`);
  options.headers.set('Content-Type', 'application/json;charset=UTF-8');
} else {
  // we have to add the token to the url object
  url.headers.set('Authorization', `Bearer ${token}`);
  url.headers.set('Content-Type', 'application/json;charset=UTF-8');
}
return super.request(url, options).catch(this.catchAuthError(this));}

private catchAuthError(self: HttpService) {
// we have to pass HttpService's own instance here as `self`
return (res: Response) => {
  console.log(res);
  if (res.status === 401 || res.status === 403) {
    // if not authenticated
    console.log(res);
  }
  return Observable.throw(res);
};}

我的目标是在身份验证出错时以"false"值从登录方法返回。

提前谢谢你!

对于 rxsj <5.5,您需要使用 catch 运算符。此外,副作用不应在map运算符中处理,而应在do运算符中处理。

喜欢这个:

login(accountCredentials: AccountCredentials): Observable < boolean > {
  return this.http.post(UrlHelper.routeTo("auth/login"), JSON.stringify(accountCredentials))
    .do(n => {
      this.authService.setToken(n.json().token);
      this.globalEventsManager.login.emit();
    })
    .map(n => {
      return true;
    })
    .catch(e => false);
}

如果您使用的是 rxjs> 5.5,您唯一需要更改的是将do重命名为 tapcatch重命名为 catchError ,并将所有内容包装在 pipe 方法中。

login(accountCredentials: AccountCredentials): Observable < boolean > {
  return this.http.post(UrlHelper.routeTo("auth/login"), JSON.stringify(accountCredentials))
    .pipe(
      tap(n => {
        this.authService.setToken(n.json().token);
        this.globalEventsManager.login.emit();
      }),
      .map(n => {
        return true;
      }),
      catchError(e => false);
    )
}

最新更新