Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 Provide http interceptor based on environment

I have the following two environments in my angular-cli (v1.5.1, angular v5) application:

  1. dev
  2. prod

Dev makes use of mock data, which I provide with an http-interceptor. Pro makes use of a live rest api.

How do I provide the http-interceptor on dev, but not on pro? I already tried the following, but it doesn't work:

{
  provide: HTTP_INTERCEPTORS,
  useFactory: () => {
    if (environment.useMockBackend === true) {
      return MockHttpInterceptor;
    }
    return false;
  },
  multi: true
}
like image 533
StefanN Avatar asked Nov 02 '17 10:11

StefanN


1 Answers

In my Angular 5.2 project I used following approach.

app.module.ts

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { environment } from '../environments/environment';
import { MyInterceptor } from './my.interceptor';

const commonProviders = [/*...*/];
const nonProductionProviders = [{ 
  provide: HTTP_INTERCEPTORS,
  useClass: MyInterceptor,
  multi: true
}];

@NgModule({
  imports: [
    HttpClientModule,
    // ...
  ],
  providers: [
    ...commonProviders,
    ...!environment.production ? nonProductionProviders : []
  ]
})

my.interceptor.ts

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

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    // ...
    return next.handle(req);
  }
}
like image 101
dhilt Avatar answered Sep 30 '22 04:09

dhilt