I created an authentication service in my angular app with the help of several tutorials. The happy path is working fine, but I can't handle 401 errors etc. in this case my map function is not called.
Any ideas how to handle login errors?
login(username: string, password: string): Observable<boolean> {
return this.http.post(environment.baseUrl + '/api/authenticate', JSON.stringify({ username: username, password: password }))
.map((response: Response, error: any) => {
console.log('mapping response...', response.status.toString());
// login successful if there's a jwt token in the response
const 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;
}
});
}
You could try adding a catch like this:
return this.http.post(environment.baseUrl + '/api/authenticate', JSON.stringify({ username: username, password: password }))
.map((response: Response) => {
console.log('mapping response...', response.status.toString());
// login successful if there's a jwt token in the response
const 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(this.handleError);
private handleError(error: Response): Observable<any> {
// in a real world app, we may send the server to some remote logging infrastructure
// instead of just logging it to the console
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
Or to return false, you could change this as follows:
import 'rxjs/add/observable/of';
private handleError(error: Response): Observable<any> {
// in a real world app, we may send the server to some remote logging infrastructure
// instead of just logging it to the console
console.error(error);
return Observable.of(false);
}
You could try to:
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push(function($q) {
return {
'responseError': function(rejection){
var defer = $q.defer();
if(rejection.status == 401){
console.dir(rejection);
}
defer.reject(rejection);
return defer.promise;
}
};
});
}]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.