相關教學推薦:《angular教學》
我們在做一個後台管理系統時,需要給每個請求的請求頭裡面添加token,所以下面我們來了解一下angular的攔截器,並使用
攔截器使用
1.建立http.service.ts,用於網路請求
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.建立noop. interceptor.ts,攔截器實作代碼
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)//请求头统一添加token }) // } return next.handle(req).pipe( tap( event => { if (event instanceof HttpResponse) { console.log(event); if (event.status >= 500) { // 处理错误 } } }, error => { // token过期 服务器错误等处理 // 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 } ], // ... 省略 })
攔截器一般配合路由守衛一起使用,想了解可以看另一遍文章,路由守衛(https://blog.csdn.net/qq_44855897/article/details/106985343)
1、angular官網(https://angular.cn/guide/http#intercepting-requests-and-responses)
2、程式碼位址(https://github.com/zhuye1993/angular9-route)
更多程式相關知識,可存取:程式設計入門! !
以上是如何使用angular9攔截器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!