我的数据服务响应401状态(未经身份验证)时,我需要直接登录页面。这是我的代码
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())));
}
答案 0 :(得分:0)
允许您创建一个带有角度的http拦截器,以管理发送请求和获得响应时的动作
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;
}
}
然后您可以在模块示例中注册
@NgModule({
imports: [
HttpClientModule
],
exports: [
HttpClientModule
],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: UcmsHttpInterceptor, multi: true }
],
})
export class RestModule {