相關(guān)教程推薦:《angular教程》
攔截器統(tǒng)一添加token
我們在做一個后臺管理系統(tǒng)時,需要給每個請求的請求頭里面添加token,所以下面我們來了解一下angular的攔截器,并使用
攔截器使用
1.創(chuàng)建http.service.ts,用于網(wǎng)絡(luò)請求
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class HttpService { constructor(private http: HttpClient) { } getData () { return this.http.get('/assets/mock/data.json') } }
2.創(chuàng)建noop.interceptor.ts,攔截器實現(xiàn)代碼
import { Injectable } from '@angular/core'; import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; import { Router } from '@angular/router'; /** Pass untouched request through to the next request handler. */ @Injectable() export class NoopInterceptor implements HttpInterceptor { constructor (private router: Router) {} intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // 攔截請求,給請求頭添加token let url = req.url // 可以對url進行處理 let token = document.cookie && document.cookie.split("=")[1] // 登錄請求排除在外 // if (!url.includes('login')) { req = req.clone({ url, // 處理后的url,再賦值給req headers: req.headers.set('Authorization', token)//請求頭統(tǒng)一添加token }) // } return next.handle(req).pipe( tap( event => { if (event instanceof HttpResponse) { console.log(event); if (event.status >= 500) { // 處理錯誤 } } }, error => { // token過期 服務(wù)器錯誤等處理 // this.router.navigate(['/login']); }) ); } }
3.在app.module.ts中使用
3.1imports中引入HttpClientModule
3.2HttpService的注冊
3.3NoopInterceptor攔截器的使用
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { HttpService } from './auth/http.service'; import { NoopInterceptor } from './auth/noop.interceptor'; @NgModule({ imports: [ BrowserModule, HttpClientModule, AppRoutingModule ], providers: [ HttpService, { provide: HTTP_INTERCEPTORS, useClass: NoopInterceptor, multi: true } ], // ... 省略 })
攔截器實現(xiàn)后的效果
攔截器一般配合路由守衛(wèi)一起使用,想了解可以看另一遍文章,路由守衛(wèi)(https://blog.csdn.net/qq_44855897/article/details/106985343)
參考資料
1、angular官網(wǎng)(https://angular.cn/guide/http#intercepting-requests-and-responses)
2、代碼地址(https://github.com/zhuye1993/angular9-route)