/** * @description 發送請求 */ request = (type, params, url) => { const token = localStorage.getItem('token'); return this.http.request(type, window.API_ROOT + url, { headers: new HttpHeaders({ 'Authorization': `Token ${token}` }), body: params }); }
/** * @description 獲取用戶信息 */ getUser() { this.apiService.request('get', '', 'api/common/login_user').toPromise().then((res: any) => { }); }
①在app.module.ts的providers中引入攔截器文件npm
providers: [ { provide: HTTP_INTERCEPTORS, useClass: InterceptorService, multi: true } ],
②建立全局攔截器服務InterceptorService後端
export class InterceptorService implements HttpInterceptor { constructor(private router: Router) { } intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(req).pipe(catchError((err) => { if (err.status === 401) { this.router.navigate(['/login']); } return ErrorObservable.create(event); })); } }
npm install @auth0/angular-jwt
export function tokenGetter() { return localStorage.getItem('token'); }
在import中引入api
JwtModule.forRoot({ config: { tokenGetter: tokenGetter, whitelistedDomains: ['localhost:4200', 'test.backend.jclife.com'], blacklistedRoutes: [], throwNoTokenError: false } })
注意:域名必須得加入白名單中,不然http請求不會帶上token,致使報錯沒有權限app