Patrick Hillert
Patrick Hillert

Reputation: 2439

How to specify custom environment variables in Angular?

I would like to use another environment variable. In my case test. The reason is that I want to inject a http interceptor for my integration tests. This interceptor should only return a mocked response with predefined data and is used for testing only.

Is there an official angular-way?

So simply I want this app.module.ts:

    import { environment } from '../environments/environment';
    // ...

    export function CustomHttpProvider (backend: XHRBackend, options: RequestOptions) {
      return new HttpService(backend, options);
    }

    export function FakeHttpProvider (backend: XHRBackend, options: RequestOptions) {
      return new FakeHttpService(backend, options);
    }

    const HttpProvider = environment.test ? FakeHttpProvider : CustomHttpProvider;

    @NgModule({
      imports: [
        BrowserModule,
        HttpModule,
        BrowserAnimationsModule,

        // ... my modules + routing here
      ],
      declarations: [AppComponent],
      providers: [
        {
          provide: Http,
          useFactory: HttpProvider,
          deps: [XHRBackend, RequestOptions]
        }
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule {}

Upvotes: 1

Views: 1771

Answers (1)

ApriOri
ApriOri

Reputation: 2688

Angular CLI has a command line parameter --environment that will let you do this if you set up some class to support that.

See this blog post

This answer provides lots of information related to your question.

As a side note. For angular 1.5 I have used this plugin.

Upvotes: 1

Related Questions