脚本之家

电脑版
提示:原网页已由神马搜索转码, 内容由www.jb51.net提供.
您的位置:首页网络编程JavaScriptjavascript类库AngularJS→ Angular拦截器 httpClient

Angular项目如何使用拦截器 httpClient 请求响应处理

  更新时间:2024年06月19日 09:31:06  作者:天天向上518 
这篇文章主要介绍了Angular项目简单使用拦截器httpClient请求响应处理,目前我的Angular版本是Angular 17.3,版本中实现请求和响应的拦截处理了,这种机制非常适合添加如身份验证头、错误统一处理、日志记录等功能,需要的朋友可以参考下

1:为啥要使用拦截器 httpClient 请求响应处理,其作用我们主要是:

目前我的Angular版本是Angular 17.3,版本中实现请求和响应的拦截处理了。这种机制非常适合添加如身份验证头、错误统一处理、日志记录等功能。

======具体的操作步骤=======

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

 import { Injectable } from '@angular/core';
import { HttpResponse, HttpRequest, HttpInterceptor, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable, tap } from 'rxjs';

@Injectable({
providedIn: 'root'
})
// 用作http 请求响应的拦截器
export class MyhttpInterceptorServiceService implements HttpInterceptor {
constructor() { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// 请求前处理,可以加上 head 的token 如果需要
//console.log('Request:', req.url);
console.log('Request:=======请求前的处理=========' + req.url);
if (!req.headers.has('Authorization')) {
req = req.clone({
setHeaders: {
Authorization: 'Bearer ' + localStorage.getItem('logininfo')
}
});
console.log("请求头新增token 成功 Authorization-----------");
} else {
console.log("已经存在token,不需要新增");
}
// 发送请求,并且在响应上做文章
return next.handle(req).pipe(
tap(
event => {
if (event instanceof HttpResponse) {
// 成功响应时的处理
//console.log('Response:', event.status);
console.log('Response:====成功响应的处理============');
}
},
error => {
// 错误响应时的处理
//console.error('Error:', error.message);
console.error('Error', '=======error msg=========');
}
)
);
}
}

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

 import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './components/home/home.component';
import { TopComponent } from './components/top/top.component';
import { MenuComponent } from './components/menu/menu.component';
import { ProductComponent } from './components/product/product.component';
//primeng
import {ButtonModule} from 'primeng/button';
import { FormsModule } from '@angular/forms';
import {CalendarModule} from 'primeng/calendar';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {PanelMenuModule} from 'primeng/panelmenu';
import { BodyComponent } from './components/body/body.component';
import {TableModule} from 'primeng/table'
import {InputTextModule} from 'primeng/inputtext';
import {MessageModule} from 'primeng/message';
import {ToastModule} from 'primeng/toast';
import { TranslateModule,TranslateLoader } from '@ngx-translate/core';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { MydialogComponent } from './components/mydialog/mydialog.component';
import { MybooksComponent } from './components/mybooks/mybooks.component';
import { StudentComponent } from './components/student/student.component';
import { TeacherComponent } from './components/teacher/teacher.component';
import { WelcomeComponent } from './components/welcome/welcome.component';
import { LoginComponent } from './components/login/login.component';
//HttpClientModule, HTTP_INTERCEPTORS -----拦截器的导入
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyhttpInterceptorServiceService } from './services/myhttp-interceptor-service.service';
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http,'../assets/i18n/',".json");
}
@NgModule({
declarations: [
AppComponent,
HomeComponent,
TopComponent,
MenuComponent,
ProductComponent,
BodyComponent,
MydialogComponent,
MybooksComponent,
StudentComponent,
TeacherComponent,
WelcomeComponent,
LoginComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
ButtonModule,
FormsModule,
CalendarModule,
PanelMenuModule,
TableModule,
InputTextModule,
MessageModule,
ToastModule,
HttpClientModule,TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
providers: [{
provide: HTTP_INTERCEPTORS, //---------------
useClass: MyhttpInterceptorServiceService,
multi: true // 注意这里设置为true,因为可以有多个拦截器
}],
bootstrap: [AppComponent]
})
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:在组件中测试使用

<p>student works! 请求接口获取到用户名称为:{{userName}}</p>
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Component({
selector: 'app-student',
templateUrl: './student.component.html',
styleUrl: './student.component.scss'
})
export class StudentComponent implements OnInit {
userName: string;
constructor(private http: HttpClient) {
this.userName = "";
}
ngOnInit(): void {
this.http.get('http://www.baidu.com:4200/gateway/basic/accounts/getUserAcountList?ntid=3793831').pipe().subscribe((data?: any) => {
console.log(data);
this.userName = data.data[0].name;
})
}
}

5:测试效果

到此这篇关于Angular项目简单使用拦截器 httpClient 请求响应处理的文章就介绍到这了,更多相关Angular拦截器 httpClient内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

    • 本篇文章主要介绍了Angular网络请求的封装方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
      2018-05-05
    • 这篇文章主要介绍了Angular2生命周期钩子函数的详细介绍,Angular提供组件生命周期钩子,可以让我们更好的开发Angular应用,有兴趣的可以了解一下
      2017-07-07
    • 本篇文章主要介绍了Angular2 组件间通过@Input @Output通讯示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
      2017-08-08
    • 这篇文章主要介绍了angular4中引入echarts的方法示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
      2019-01-01
    • 这篇文章主要介绍了AngularJS实现的select二级联动下拉菜单功能,结合完整实例形式分析了AngularJS实现二级联动菜单的具体操作步骤与相关实现技巧,需要的朋友可以参考下
      2017-10-10
    • 这篇文章主要介绍了测试IE浏览器对JavaScript的AngularJS的兼容性的方法,尽管随着Windows10的近期上市,IE浏览器即将成为历史...需要的朋友可以参考下
      2015-06-06
    • 这篇文章主要介绍了Angular2 (RC4) 路由与导航的相关资料,需要的朋友可以参考下
      2016-09-09
    • 本文给大家介绍使用Angularjs实现多个页面共享数据的方式,通过定义一个共享服务service来实现此功能,对angularjs共享数据相关知识感兴趣的朋友一起学习
      2016-03-03
    • 本篇文章给大家介绍在angularjs中自定义一个有关表格的directive,涉及到angularjs directive相关知识,对本文感兴趣的朋友一起学习吧
      2016-01-01
    • 本文主要介绍AngularJs Injecting Services Into Controllers的知识,这里整理了一下相关资料,及示例代码,帮助大家学习和理解,有兴趣的小伙伴可以参考下
      2016-09-09

    最新评论