首页 > 其他分享 >Angular项目简单使用拦截器 httpClient 请求响应处理

Angular项目简单使用拦截器 httpClient 请求响应处理

时间:2024-06-18 12:01:18浏览次数:9  
标签:拦截器 http console component Angular components import angular httpClient

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:测试效果

 

 

 

 

标签:拦截器,http,console,component,Angular,components,import,angular,httpClient
From: https://www.cnblogs.com/Fengge518/p/18254060

相关文章

  • Angular项目路由配置与导航守卫
    1:一个项目的所有组件如下测试案例:AppComponent,HomeComponent,TopComponent,MenuComponent,ProductComponent,BodyComponent,MydialogComponent,MybooksComponent,StudentComponent,TeacherComponent,WelcomeComponent,......
  • Angular 18+ 高级教程 – Memory leak, unsubscribe, onDestroy
    何谓 MemoryLeak?Angular是SPA(Single-pageapplication)框架,用来开发SPA。SPA最大的特点就是它不刷新页面,不刷新就容易造成memoryleak。举个例子:有一个页面A,我们写了一个setInterval执行一些代码(比如autoplay幻灯片)。当用户离开页面A去页面B时,传统网......
  • 浅析Mybatis拦截器
    一、背景最近针对项目中出现的慢sql,我们使用自定义Mybatis拦截器,结合DUCC动态配置慢sql阈值,来监控慢sql并报警,提前发现风险点。借着这个契机,浅析下Mybatis拦截器原理,个人理解,不足之处请指正。二、Mybatis拦截器Mybatis使用plugin来拦截方法调用,所以MyBatisplugin也称为:Mybatis......
  • 过滤器和拦截器的区别
    一、拦截器和过滤器的区别1、过滤器和拦截器触发时机不一样,过滤器是在请求进入容器后,但请求进入servlet之前进行预处理的。请求结束返回也是,是在servlet处理完后,返回给前端之前。2、拦截器可以获取IOC容器中的各个bean,而过滤器就不行,因为拦截器是spring提供并管理的,spring的功能......
  • Angular 集成 StreamSaver 大文件下载
    应用场景:实现目标:在网页端实现大文件(文件大小>=2G)断点续传实际方案:发送多次请求,每次请求一部分文件数据,然后通过续写将文件数据全部写入.难点:无法实现文件续写,最后采用 StreamSaver来解决这个问题. 1.首先从github将 StreamSaver拉取下来.Strea......
  • Angular Material 18+ 高级教程 – Material Form Field
    介绍FormField或TextField是MaterialDesign独有的设计风格。它长这样注:MaterialDesign管它叫TextField,AngularMaterial管它叫FormField。我们不要乱,本篇统一叫FormField就好。顾名思义,Form代表表单,Field代表<fieldset>里的field。拿一个 W3Schools......
  • SpringBoot拦截器Interceptor讲解
    1.拦截器介绍1.1拦截器是什么拦截器是一种动态拦截方法调用的机制,相当于过滤器;拦截器是Spring框架中提供的,用来动态拦截控制器方法的执行。1.2拦截器作用拦截请求,在指定方法调用前后,根据业务需求编写处理逻辑。在拦截器当中,通常做一些通用性的操作,比如:我们可以通过拦截......
  • httpclient,轻量级idea集成测试工具
    优点:不用新开一个网页,具有测试数据保存功能,不需要配置即用(对比swagger)   不会特别占内存(对比postman) 使用方法:idea中安装插件controller方法中点击 选择对应action 即可自动生成测试,点击左侧三角即可测试。但是数据内容需要自己填写如下:###分页查询POST{......
  • 【Spring Boot 整合 Angular】
    今天我们尝试SpringBoot整合Angular,并决定建立一个非常简单的SpringBoot微服务,使用Angular作为前端渲编程语言进行前端页面渲染.基础环境技术版本Java1.8+SpringBoot1.5.x创建项目初始化项目bashmvnarchetype:generate-DgroupId=com.edurt.sli.sliss-Dartifact......
  • 过滤器(Filter)和拦截器(Interceptor)的区别
     过滤器(Filter)和拦截器(Interceptor)在JavaWeb开发用于拦截和处理请求的机制,但有显著的区别和不同的业务场景。 概念:过滤器(Filter)是基于servlet容器回调实现,可以拦截请求和响应的所有内容,包括静态资源和动态资源。拦截器(Interceptor)是基于Spring框架,只作用于Spring的上下......