Angular專案簡單使用攔截器 httpClient 請求響應處理

天天向上518發表於2024-06-18

1:為啥要使用攔截器 httpClient 請求響應處理,其作用我們主要是:

目前我的Angular版本是Angular 17.3,版本中實現請求和響應的攔截處理了。這種機制非常適合新增如身份驗證頭、錯誤統一處理、日誌記錄等功能。

======具體的操作步驟=======

2:注入服務:ng g s services/myhttp-interceptorService

 1 import { Injectable } from '@angular/core';
 2 import { HttpResponse, HttpRequest, HttpInterceptor, HttpHandler, HttpEvent } from '@angular/common/http';
 3 import { Observable, tap } from 'rxjs';
 4 
 5 @Injectable({
 6   providedIn: 'root'
 7 })
 8 // 用作http 請求響應的攔截器
 9 export class MyhttpInterceptorServiceService implements HttpInterceptor {
11   constructor() { }
12   intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
13     // 請求前處理,可以加上 head 的token 如果需要
14     //console.log('Request:', req.url);
15     console.log('Request:=======請求前的處理=========' + req.url);
16     if (!req.headers.has('Authorization')) {
17       req = req.clone({
18         setHeaders: {
19           Authorization: 'Bearer ' + localStorage.getItem('logininfo')
20         }
21       });
22       console.log("請求頭新增token 成功 Authorization-----------");
23     } else {
24       console.log("已經存在token,不需要新增");
25     }
26     // 傳送請求,並且在響應上做文章
27     return next.handle(req).pipe(
28       tap(
29         event => {
30           if (event instanceof HttpResponse) {
31             // 成功響應時的處理
32             //console.log('Response:', event.status);
33             console.log('Response:====成功響應的處理============');
34           }
35         },
36         error => {
37           // 錯誤響應時的處理
38           //console.error('Error:', error.message);
39           console.error('Error', '=======error msg=========');
40         }
41       )
42     );
43   }
44 }

3:配置到根模組中 app.module.ts

 1 import { NgModule } from '@angular/core';
 2 import { BrowserModule } from '@angular/platform-browser';
 3 
 4 import { AppRoutingModule } from './app-routing.module';
 5 import { AppComponent } from './app.component';
 6 import { HomeComponent } from './components/home/home.component';
 7 import { TopComponent } from './components/top/top.component';
 8 import { MenuComponent } from './components/menu/menu.component';
 9 import { ProductComponent } from './components/product/product.component';
10 
11 
12 //primeng
13 import {ButtonModule} from 'primeng/button';
14 import { FormsModule } from '@angular/forms';
15 import {CalendarModule} from 'primeng/calendar';
16 import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
17 
18 import {PanelMenuModule} from 'primeng/panelmenu';
19 import { BodyComponent } from './components/body/body.component';
20 
21 import {TableModule} from 'primeng/table'
22 import {InputTextModule} from 'primeng/inputtext';
23 import {MessageModule} from 'primeng/message';
24 import {ToastModule} from 'primeng/toast';
25 
26 import { TranslateModule,TranslateLoader } from '@ngx-translate/core';
27 import { HttpClient, HttpClientModule } from '@angular/common/http';
28 import { TranslateHttpLoader } from '@ngx-translate/http-loader';
29 import { MydialogComponent } from './components/mydialog/mydialog.component';
30 import { MybooksComponent } from './components/mybooks/mybooks.component';
31 import { StudentComponent } from './components/student/student.component';
32 import { TeacherComponent } from './components/teacher/teacher.component';
33 import { WelcomeComponent } from './components/welcome/welcome.component';
34 import { LoginComponent } from './components/login/login.component';
35 
36 //HttpClientModule, HTTP_INTERCEPTORS -----攔截器的匯入
37 import { HTTP_INTERCEPTORS } from '@angular/common/http';
38 import { MyhttpInterceptorServiceService } from './services/myhttp-interceptor-service.service';
39 
40 export function HttpLoaderFactory(http: HttpClient) {
41   return new TranslateHttpLoader(http,'../assets/i18n/',".json");
42 }
43 @NgModule({
44   declarations: [
45     AppComponent,
46     HomeComponent,
47     TopComponent,
48     MenuComponent,
49     ProductComponent,
50     BodyComponent,
51     MydialogComponent,
52     MybooksComponent,
53     StudentComponent,
54     TeacherComponent,
55     WelcomeComponent,
56     LoginComponent
57   ],
58   imports: [
59     BrowserModule,
60     AppRoutingModule,
62     BrowserAnimationsModule,
64     ButtonModule,
65     FormsModule,
66     CalendarModule,
68     PanelMenuModule,
70     TableModule,
71     InputTextModule,
72     MessageModule,
73     ToastModule,
74 
75 HttpClientModule,TranslateModule.forRoot({
76   loader: {
77     provide: TranslateLoader,
78     useFactory: HttpLoaderFactory,
79     deps: [HttpClient]
80   }
81 })
84   ],
85   providers: [{
86     provide: HTTP_INTERCEPTORS,   //---------------
87     useClass: MyhttpInterceptorServiceService,
88     multi: true   // 注意這裡設定為true,因為可以有多個攔截器
89   }],
90   bootstrap: [AppComponent]
91 })
92 export class AppModule { }
//重點如下配置:HttpClientModule, HTTP_INTERCEPTORS 攔截器的匯入
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyhttpInterceptorServiceService } from './services/myhttp-interceptor-service.service';
providers: [{ provide: HTTP_INTERCEPTORS, useClass: MyhttpInterceptorServiceService, multi:
true // 注意這裡設定為true,因為可以有多個攔截器 }],

4:在元件中測試使用

 1 <p>student works! 請求介面獲取到使用者名稱稱為:{{userName}}</p>
 2 
 3 import { Component, OnInit } from '@angular/core';
 4 import { HttpClient } from '@angular/common/http';
 5 import { Injectable } from '@angular/core';
 6 @Component({
 7   selector: 'app-student',
 8   templateUrl: './student.component.html',
 9   styleUrl: './student.component.scss'
10 })
11 export class StudentComponent implements OnInit {
12   userName: string;
13   constructor(private http: HttpClient) {
14     this.userName = "";
15   }
16   ngOnInit(): void {
17     this.http.get('http://www.baidu.com:4200/gateway/basic/accounts/getUserAcountList?ntid=3793831').pipe().subscribe((data?: any) => {
18       console.log(data);
19       this.userName = data.data[0].name;
20     })
21   }
22 }

5:測試效果

相關文章