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

Angular项目简单使用拦截器 httpClient 请求响应处理的更多相关文章

  1. springboot(五).如何在springboot项目中使用拦截器

    在每个项目中,拦截器都是我们经常会去使用的东西,基本上任一一个项目都缺不了拦截器的使用. 如日志记录.登录验证,session验证等,都需要拦截器来拦截URL请求,那springboot中的拦截器是如 ...

  2. vue+axois 封装请求+拦截器(请求锁+统一错误)

     需求 封装常用请求 拦截器-请求锁 统一处理错误码 一.封装常用的请求 解决痛点:不要每一个模块的api都还要写get,post,patch请求方法.直接将这些常用的方法封装好. 解决方案:写一个类 ...

  3. Java过滤器处理Ajax请求,Java拦截器处理Ajax请求,拦截器Ajax请求

    Java过滤器处理Ajax请求,Java拦截器处理Ajax请求,拦截器Ajax请求 >>>>>>>>>>>>>>&g ...

  4. spring mvc 通过拦截器记录请求数据和响应数据

    spring mvc 能过拦截器记录请求数据记录有很多种方式,主要有以下三种: 1:过滤器 2:HandlerInterceptor拦截器 3:Aspect接口控制器 但是就我个人所知要记录返回的数据 ...

  5. springweb项目自定义拦截器修改请求报文头

    面向切面,法力无边,任何脏活累活,都可以从干干净净整齐划一的业务代码中抽出来,无非就是加一层,项目里两个步骤间可以被分层的设计渗透成筛子. 举个例子: 最近我们对接某银行接口,我们的web服务都是标准 ...

  6. Apache httpclient拦截器对请求进行签名

    Apahce httpclient 提供HttpRequestInterceptor和HttpResponseInterceptor两种拦截器分别处理请求和响应数据,下面讲一下如何对http请求进行拦 ...

  7. 五、Vue:使用axios库进行get和post、用拦截器对请求和响应进行预处理、Mock(数据模拟)

    一.axios [应用]进行请求和传表单 [axios中文档]:https://www.kancloud.cn/yunye/axios/234845 [vue-axios]:https://cn.vu ...

  8. springmvc实现简单的拦截器

    SpringMVC 中的Interceptor 拦截请求是通过HandlerInterceptor 来实现的.在SpringMVC 中定义一个Interceptor 非常简单,主要有两种方式,第一种方 ...

  9. ssm项目中使用拦截器加上不生效解决方案

    在很多时候,需要拦截器来帮助我们完成一些特定的工作,比如获取请求的参数,本身在request这种获取数据就是一次磁盘的io, 如果在filter中获取了参数,那么在controller中就不能获取相关 ...

  10. 配置简单的拦截器java中

    springMVC.xml文件中==== <!-- 拦截器 --> <mvc:interceptors> <mvc:interceptor> <mvc:map ...

随机推荐

  1. HTML中元素分类与对应的CSS样式特点

    元素就是标签,布局中常用的有三种标签,块元素.内联元素.内联块元素,了解这三种元素的特性,才能熟练的进行页面布局. 块元素 块元素,也可以称为行元素,布局中常用的标签如:div.p.ul.li.h1~ ...

  2. dotnet 记 TaskCompletionSource 的 SetException 可能将异常记录到 UnobservedTaskException 的问题

    本文将记录 dotnet 的一个已知问题,且是设计如此的问题.假定有一个 TaskCompletionSource 对象,此对象的 Task 没有被任何地方引用等待.在 TaskCompletionS ...

  3. 2019-8-31-dotnet-core-使用-PowerShell-脚本

    title author date CreateTime categories dotnet core 使用 PowerShell 脚本 lindexi 2019-08-31 16:55:58 +08 ...

  4. Mysql带条件取多条随机记录

    有个文章段落表part,有两种类型的段落,即part_type取1或2,要从表中随机取多条任意类型的段落,比如3条. 方法一 ORDER BY后接RAND() select * from part w ...

  5. github只下载某个文件或文件夹(使用GitZip插件)

    安装GitZip插件 (此安装过程需要梯子(不懂"梯子",百度一下就明白)) 1. 打开插件管理页面 方法一:打开Chrome浏览器(Edge浏览器同理),在Chrom地址栏输入c ...

  6. .NET Aspire 预览版 6 发布

    .NET Aspire 预览版 6 引入了一系列重大更新,主要包括 API 的重大更改.安全性和可靠性的提升.新的资源和组件.应用程序主机的更新.测试支持.模板更新.组件更新.Azure 配置包的更新 ...

  7. B/S 结构系统的 缓存机制(Cookie) 以及基于 cookie 机制实现 oa 十天免登录的功能

    B/S 结构系统的 缓存机制(Cookie) 以及基于 cookie 机制实现 oa 十天免登录的功能 @ 目录 B/S 结构系统的 缓存机制(Cookie) 以及基于 cookie 机制实现 oa ...

  8. 三、Prophecis 一站式云原生机器学习平台

    Prophecis 是微众银行自研大数据平台套件 WeDataSphere 的核心应用工具之一,为用户提供了全栈的机器学习应用开发与部署解决方案.作为WeDataSphere 功能工具应用系统,Pro ...

  9. 简说Python之循环语句

    目录 Python的运算逻辑 Python条件语句 Python循环语句 Python while循环 Python for 循环 条件语句和循环语句是程序常用的一种基础语法,从语言上来说,能说清楚的 ...

  10. 在Linux下想要删除一个目录需要怎样的权限

    场景一 在Home目录下创建一个目录dirtest,然后使用chmod 333 dirtest修改目录权限.这时候dirtest的权限为d-wx-wx-wx,如果执行rm -r dirtest可以进行 ...