Angular catch HTTP异常

时间:2018-04-18 07:44:38

标签: angular

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

我的user.service:

  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”值。

提前谢谢!

1 个答案:

答案 0 :(得分:1)

对于rxsj&lt; 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&gt; 5.5,您唯一需要更改的是将do重命名为tap,将catch重命名为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);
    )
}