kaspertorp kaspertorp - 14 days ago 12
reST (reStructuredText) Question

Angular 2 catching 401 reponse

working on Angular2/Node.

For loggin in we have the following

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


problem being that i get the following error


Argument of type '(err: any) => boolean' is not assignable to
parameter of type '(err: any, caught: Observable) =>
ObservableInput'. Type 'boolean' is not assignable to type
'ObservableInput'.


And i'm unsure of what i need to change to get it to be able to catch the 401s

For testing the login looks as following

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


edit: Seems i'm missing a point about using .catch and subscribe together, but still unsure of how and why.

Answer

You can delete this code:

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

Or add logging and throwing exception instead:

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

Also add in subsribe:

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