问题
I need to direct to login page while my data service response to 401 status(unauthenticated ).Here is my code
get_data(url,auth=true){
//......url : url path......
//....auth : true api auth required,false no api required....
var get_url = API_URL + url;
var headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
if(auth==true){
var localStore = JSON.parse(localStorage.getItem('currentUser'));
if (localStorage.getItem("currentUser") != null) {
headers.append("Authorization", "Bearer " + localStore.token);
}else{
headers.append("Authorization", "Bearer ");
//this.router.navigate(['/login']);
}
}
let options = new RequestOptions({ headers });
return this.http.get(get_url, options) .pipe((map(res => res.json())));
}
回答1:
Allow you can create an http interceptor in angular to manage action when request are sent and when you get response
http.interceptor.ts
import { throwError as observableThrowError, Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse } from '@angular/common/http';
import { Injectable, ErrorHandler } from '@angular/core';
import { UserStore } from '../store/user.store';
import { Router } from '@angular/router';
import * as HttpStatus from 'http-status-codes';
@Injectable()
export class SimpleHttpInterceptor implements HttpInterceptor {
constructor(private router: Router, private userStore: UserStore) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
req = this.addAuthentication(req);
return next.handle(req).pipe(catchError((err) => {
if (err.status === HttpStatus.UNAUTHORIZED) {
this.router.navigate(['/login']); //go to login fail on 401
}
return observableThrowError(err);
}));
}
//here you add the bearer in every request
addAuthentication(req: HttpRequest<any>): HttpRequest<any> {
const headers: any = {};
const authToken = this.userStore.getToken(); // get the token from a service
if (authToken) {
headers['authorization'] = authToken; // add it to the header
req = req.clone({
setHeaders: headers
});
}
return req;
}
}
You can then registrer it in a module example
@NgModule({
imports: [
HttpClientModule
],
exports: [
HttpClientModule
],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: UcmsHttpInterceptor, multi: true }
],
})
export class RestModule {
来源:https://stackoverflow.com/questions/52372264/how-to-handle-401-unauthenticated-error-in-angular-6