Angular項(xiàng)目如何使用攔截器?httpClient?請求響應(yīng)處理
1:為啥要使用攔截器 httpClient 請求響應(yīng)處理,其作用我們主要是:
目前我的Angular版本是Angular 17.3,版本中實(shí)現(xiàn)請求和響應(yīng)的攔截處理了。這種機(jī)制非常適合添加如身份驗(yàn)證頭、錯(cuò)誤統(tǒng)一處理、日志記錄等功能。
======具體的操作步驟=======
2:注入服務(wù):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 請求響應(yīng)的攔截器
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("已經(jīng)存在token,不需要新增");
}
// 發(fā)送請求,并且在響應(yīng)上做文章
return next.handle(req).pipe(
tap(
event => {
if (event instanceof HttpResponse) {
// 成功響應(yīng)時(shí)的處理
//console.log('Response:', event.status);
console.log('Response:====成功響應(yīng)的處理============');
}
},
error => {
// 錯(cuò)誤響應(yīng)時(shí)的處理
//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 -----攔截器的導(dǎo)入
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 // 注意這里設(shè)置為true,因?yàn)榭梢杂卸鄠€(gè)攔截器
}],
bootstrap: [AppComponent]
})
export class AppModule { }//重點(diǎn)如下配置:HttpClientModule, HTTP_INTERCEPTORS 攔截器的導(dǎo)入
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyhttpInterceptorServiceService } from './services/myhttp-interceptor-service.service';
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: MyhttpInterceptorServiceService,
multi: true // 注意這里設(shè)置為true,因?yàn)榭梢杂卸鄠€(gè)攔截器
}],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:測試效果

到此這篇關(guān)于Angular項(xiàng)目簡單使用攔截器 httpClient 請求響應(yīng)處理的文章就介紹到這了,更多相關(guān)Angular攔截器 httpClient內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
AngularJS實(shí)踐之使用ng-repeat中$index的注意點(diǎn)
最近通過客戶的投訴主要到在ng-repeat中使用了$index引發(fā)的一個(gè)bug,下面一起來看看這個(gè)錯(cuò)誤是如何引發(fā)的, 以及如何避免這種bug產(chǎn)生,然后說說我們從中得到的經(jīng)驗(yàn)和教訓(xùn)。有需要的朋友們可以參考借鑒,下面來一起看看吧。2016-12-12
詳解Angular CLI + Electron 開發(fā)環(huán)境搭建
本篇文章主要介紹了Angular CLI + Electron 開發(fā)環(huán)境搭建,具有一定的參考價(jià)值,有興趣的可以了解一下2017-07-07
Angular中的結(jié)構(gòu)指令模式及使用詳解
這篇文章主要為大家介紹了Angular中的結(jié)構(gòu)指令模式及使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
angular動態(tài)刪除ng-repaeat添加的dom節(jié)點(diǎn)的方法
本篇文章主要介紹了angular動態(tài)刪除ng-repaeat添加的dom節(jié)點(diǎn)的方法,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2017-07-07
解決nodejs中使用http請求返回值為html時(shí)亂碼的問題
下面小編就為大家?guī)硪黄鉀Qnodejs中使用http請求返回值為html時(shí)亂碼的問題。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-02-02
angular實(shí)現(xiàn)圖片懶加載實(shí)例代碼
本篇文章主要介紹了angular實(shí)現(xiàn)圖片懶加載實(shí)例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-06-06

