2016-11-22 282 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) => {