Angular7/8HttpClient拦截器:模拟HTTP请求示例

分享于 

7分钟阅读

Angular

  繁體

在本教程中,我们将通过示例学习使用Angular HttpClient拦截器模拟Angular 8应用程序中的http请求。

设置Angular HttpClient

接下来,需要在项目中设置HttpClient,打开src/app/app.module.ts文件:


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';


@NgModule({
 declarations: [
 AppComponent
 ],
 imports: [
 BrowserModule,
 AppRoutingModule,
 HttpClientModule
 ],
 providers: [],
 bootstrap: [AppComponent]
})
export class AppModule { }

创建Angular拦截器

配置Angular HttpClient之后,你需要创建拦截器,在项目的src/app文件夹中,创建一个http.interceptor.ts,并添加以下代码:


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


@Injectable()
export class MockHttpCalIInterceptor implements HttpInterceptor {
 constructor(private injector: Injector) {}

 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
 console.log('Intercepted request' + request.url);
 return next.handle(request);
 }
}


注册HTTP拦截器

接下来,你需要注册拦截器,以便Angular能够识别它。打开src/app/app.module.ts文件


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

import { MockHttpCalIInterceptor } from './http.interceptor';


```ts
@NgModule({
 declarations: [
 AppComponent
 ],
 imports: [
 BrowserModule,
 AppRoutingModule,
 HttpClientModule
 ],
 providers: [{
 provide: HTTP_INTERCEPTORS,
 useClass: MockHttpCalIInterceptor,
 multi: true
 }],
 bootstrap: [AppComponent]
})
export class AppModule { }

配置typeScript以导入本地JSON文件

打开tsconfig.json文件,并在compilerOptions项下添加"resolveJsonModule": true选项:


{
 "compileOnSave": false,
 "compilerOptions": {
 ...
 "resolveJsonModule": true,
 ...
}

现在,你可以使用typeScript import语句在Angular项目中导入JSON文件。

截获URL,并返回模拟的JSON数据

现在,修改HTTP拦截器,只拦截http://localhost:3000/products URL,并从本地JSON文件返回一些数据。

首先,在data.json文件夹中创建一个src/app文件,并添加模拟数据:


[
 {
 "id": 1,
 "name": "Licensed Frozen Hat",
 "description": "Incidunt et magni est ut.",
 "price": "170.00",
 "imageUrl": "https://source.unsplash.com/1600x900/?product",
 "quantity": 56840
 },
 {
 "id": 2,
 "name": "Rustic Concrete Chicken",
 "description": "Sint libero mollitia.",
 "price": "302.00",
 "imageUrl": "https://source.unsplash.com/1600x900/?product",
 "quantity": 9358
 },
 {
 "id": 3,
 "name": "Fantastic Metal Computer",
 "description": "In consequuntur cupiditate et unde minus.",
 "price": "279.00",
 "imageUrl": "https://source.unsplash.com/1600x900/?product",
 "quantity": 90316
 }
]



Next, you need to import this JSON file inside the interceptor file and return it as an `HttpResponse`:

```ts
import { Injectable, Injector } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import * as data from './data.json';

const PRODUCTS_URL ="http://localhost:3000/products";

@Injectable()
export class MockHttpCalIInterceptor implements HttpInterceptor {
 constructor(private injector: Injector) {}

 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
 console.log('Intercepted request: ' + request.url);
 if (request.url === PRODUCTS_URL) {
 console.log('Loaded from JSON: ' + request.url);
 return of(new HttpResponse({ status: 200, body: ((data) as any).default }));
 }
 return next.handle(request);

 }
}


步骤7-测试你的Angular拦截器

现在,测试这个HTTP拦截器,simpy需要向http://localhost:3000/products发送一个请求,看看我们是否收到JSON数据:


import { Component, OnInit } from '@angular/core';
import { HttpClient } from "@angular/common/http";

const PRODUCTS_URL = "http://localhost:3000/products";

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
 title = 'Angular Example';

 constructor(private httpClient: HttpClient){}
 ngOnInit(){
 this.httpClient.get(PRODUCTS_URL).subscribe((data)=>{
 console.log(data);
 })
 }
}


INT  angular  HTTP  Request  requests  mock  
相关文章