I have the following two environments in my angular-cli (v1.5.1, angular v5) application:
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
}
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With