AngularJS

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > AngularJS > Angular拦截器 httpClient

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

作者:天天向上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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文