淺談angular9中攔截器的用法(轉(zhuǎn)載)

本篇文章和大家一起聊聊angular9中攔截器的使用。有一定的參考價(jià)值,有需要的朋友可以參考一下,希望對大家有所幫助。

相關(guān)教程推薦:《angular教程

攔截器統(tǒng)一添加token

我們在做一個(gè)后臺管理系統(tǒng)時(shí),需要給每個(gè)請求的請求頭里面添加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,攔截器實(shí)現(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進(jìn)行處理
    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) {
            // 處理錯(cuò)誤
           }
          }
         },
         error => {
          // token過期 服務(wù)器錯(cuò)誤等處理
        //   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 }
   ],
   // ... 省略})

攔截器實(shí)現(xiàn)后的效果

攔截器一般配合路由守衛(wèi)一起使用。

更多編程相關(guān)知識,請?jiān)L問:編程學(xué)習(xí)課程??!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容