2016-11-22 185 views
0

在Angular2/Node上工作。Angular 2捕获401响应

对于洛在我们的

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; 
    } 
    }); 

问题是,我得到以下错误

参数类型的下列“(ERR:任何)=>布尔”不是分配给 参数类型为'(err:any,caught:Observable)=> ObservableInput'。类型'boolean'不可分配给类型 'ObservableInput'。

而我不能确定什么,我需要改变,以得到它能够赶上401S

为了测试登录看起来如下

this.webapiService.login("[email protected]","moneyIsGood").subscribe(result => { 
    if (result === true) { 
    console.log('Username or password is correct'); 
    } else { 
    console.log('Username or password is incorrect'); 
    } 
}); 

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

+0

你可以检查:[Angular2:HTTP错误处理](http://stackoverflow.com/questions/36628498/angular2-http-error-handling) –

回答

2

错误,您可以删除此代码:

.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); 
}); 

另外在subsribe添加:

this.webapiService.login("[email protected]","moneyIsGood").subscribe(result => { 
    console.log('Username or password is correct'); 
    }, error => { 
     if (error.status === 401){ 
     console.log('Username or password is incorrect'); 
     } 
}); 
1

你能赶上这样的

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