Skip to content

Instantly share code, notes, and snippets.

@zzpmaster
Created March 22, 2021 03:10
Show Gist options
  • Save zzpmaster/c39d89ccfd9987d9471feccbb8cc3673 to your computer and use it in GitHub Desktop.
Save zzpmaster/c39d89ccfd9987d9471feccbb8cc3673 to your computer and use it in GitHub Desktop.
Angular Create multi-instance HttpClient
import { Component, Inject, InjectionToken } from "@angular/core";
import { HttpClient, HttpXhrBackend } from "@angular/common/http";
import { Observable } from "rxjs/Observable";
// import { CUSTOMER_HTTP_CLENT } from "./app.module";
export const CUSTOMER_HTTP_CLENT = new InjectionToken("xx");
@Component({
selector: "my-app",
template: `
<div>
<h3>Response</h3>
{{ response | async | json }}
</div>
<button (click)="request()">Make request</button>
`
})
export class AppComponent {
response: Observable<any>;
constructor(@Inject(CUSTOMER_HTTP_CLENT) private httpClient: HttpClient) {}
request() {
const req = new HttpRequest(
"GET",
"https://jsonplaceholder.typicode.com/posts/1"
);
const i1Handler = new HttpInterceptorHandler(this.backend, new I1());
const i2Handler = new HttpInterceptorHandler(i1Handler, new I2());
this.response = i2Handler.handle(req);
this.httpClient
.get("https://jsonplaceholder.typicode.com/posts/1")
.subscribe(data => console.log(data));
}
}
import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { AppComponent, CUSTOMER_HTTP_CLENT } from "./app.component";
import {
HTTP_INTERCEPTORS,
HttpBackend,
HttpClientModule,
HttpClient
} from "@angular/common/http";
import { I1, I2 } from "./interceptors";
// 返回新的httpclient实例
function createHttpClient(backend: HttpBackend): HttpClient {
return new HttpClient(backend);
}
@NgModule({
imports: [BrowserModule, HttpClientModule],
declarations: [AppComponent],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: I1,
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: I2,
multi: true
},
{
provide: CUSTOMER_HTTP_CLENT,
useFactory: createHttpClient,
deps: [HttpBackend]
}
],
bootstrap: [AppComponent]
})
export class AppModule {}
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class I1 implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const modified = req.clone({setHeaders: {'Custom-Header-1': '1'}});
return next.handle(modified);
}
}
@Injectable()
export class I2 implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const modified = req.clone({setHeaders: {'Custom-Header-2': '2'}});
return next.handle(modified);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment