Angular 2捕捉401响应

时间:2016-11-22 11:47:54

标签: node.js rest http angular service

在Angular2 / Node上工作。

对于登录我们有以下

login(username: string, password: string): Observable<boolean> {
  return this.http.post('http://localhost:3000/api/login', { email: username, password: password })
  .map((response: Response) => {
    // login successful if there's a jwt token in the response

    let token = response.json() && response.json().token;
    if (token) {
      // set token property
      this.token = token;

      // store username and jwt token in local storage to keep user logged in between page refreshes
      localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token }));
      // return true to indicate successful login
      return true;
    } else {
      // return false to indicate failed login
      return false;
    }
  }).catch(err =>{
    if (err.status === 401)
    {
      console.log("caught 401 exception");
      return false;
    }
  });

问题是我收到以下错误

  

类型的参数&#39;(错误:任何)=&gt;布尔&#39;不能转让给   参数类型&#39;(错误:任何,捕获:可观察)=&gt;   ObservableInput&#39 ;.输入&#39;布尔&#39;不能分配给类型   &#39; ObservableInput&#39;

我不确定我需要改变什么才能让它能够抓住401s

对于测试,登录看起来如下

this.webapiService.login("Donald@geek.com","moneyIsGood").subscribe(result => {
  if (result === true) {
    console.log('Username or password is correct');
  } else {
    console.log('Username or password is incorrect');
  }
});

编辑:似乎我错过了关于一起使用.catch和订阅的观点,但仍然不确定如何以及为什么。

2 个答案:

答案 0 :(得分:3)

您可以删除此代码:

.catch(err =>{
    if (err.status === 401)
    {
      console.log("caught 401 exception");
      return false;
    }
  });

或者添加日志记录并抛出异常:

.catch(err => {
       console.log("caught exception" + err.status);
       return Observable.throw(err);
 });

还添加订阅:

this.webapiService.login("Donald@geek.com","moneyIsGood").subscribe(result => {
     console.log('Username or password is correct');
   }, error => {
      if (error.status === 401){
        console.log('Username or password is incorrect');
      }
});

答案 1 :(得分:1)

你可以像那样抓住错误

this.http.post('http://localhost:3000/api/login', { email: username, password: password })
.catch((error: any) => this.handleError(error))
.map((response: Response) => {
相关问题