Skip to content

Instantly share code, notes, and snippets.

View maxkoretskyi's full-sized avatar

Max Koretskyi maxkoretskyi

View GitHub Profile
export class AppComponent {
response: Observable<any>;
constructor(private backend: HttpXhrBackend) {}
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);
}
export class I1 implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const modified = req.clone({setHeaders: {'Custom-Header-1': '1'}});
// passing control to the handler in the chain
return next.handle(modified);
}
}
export class AppComponent {
response: Observable<any>;
constructor(
private backend: HttpBackend,
@Inject(HTTP_INTERCEPTORS) private interceptors: HttpInterceptor[]) {}
request() {
const req = new HttpRequest('GET', 'https://jsonplaceholder.typicode.com/posts/1');
const i2Handler = this.interceptors.reduceRight(
(next, interceptor) => new HttpInterceptorHandler(next, interceptor), this.backend);
@NgModule({
providers: [
{
provide: HttpHandler,
useFactory: interceptingHandler,
deps: [HttpBackend, [@Optional(), @Inject(HTTP_INTERCEPTORS)]],
}
]
})
export class HttpClientModule {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
...
return next.handle(authReq);
}
const events$: Observable<HttpEvent<any>> = of(req).pipe(
concatMap((req: HttpRequest<any>) => this.handler.handle(req))
);
request() {
const url = 'https://jsonplaceholder.typicode.com/posts/1';
this.response = this.http.get(url, {observe: 'body'});
}
const events$: Observable<HttpEvent<any>> = of(req).pipe(...)
if (options.observe === 'events') {
return events$;
}
const res$: Observable<HttpResponse<any>> =
events$.pipe(filter((event: HttpEvent<any>) => event instanceof HttpResponse));
if (options.observe === 'response') {
@NgModule({
imports: [BrowserModule, HttpClientModule],
declarations: [AppComponent],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: I1,
multi: true
},
{
export class HttpClient {
constructor(private handler: HttpHandler) {}
request(...): Observable<any> {
...
const events$: Observable<HttpEvent<any>> =
of(req).pipe(concatMap((req: HttpRequest<any>) => this.handler.handle(req)));
...
}
}