Angular-cli: conditional import using environment variable

Is there a way to conditionally change import based on environment variable in angular -cli@1.0.0-beta.16 ? I try to do this in such a way as not to require code changes in how services are imported into the client code, but if necessary, I can specify the assembly flag for exchange in mock services.

There is a sample that I tried to use from this post :

File structure:

MyService
    MyServiceMock.ts
    MyServiceReal.ts
    index.ts

And in your index.ts you can have the following:

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

export const MyService = environment.mock ?
    require('./MyServiceMock').MyServiceMock:
    require('./MyServiceReal').MyServiceReal;

And in your client code import MyService:

import MyService from './myservice/index';

The page loads, and I see the dependency introduced when passing the code, however there are compilation errors (which, in my opinion, are TypeScript errors) in the lines Cannot find name 'MyService'.

+4
2

- . Angular providers

providers: [
  Any,
  Dependencies
  {
    provide: MyService, 
    useFactory: (any: Any, dependencies: Dependencies) => {
      if (environment.production) {
        return new MyService(any, dependencies);
      } else {
        return new MockMyService(any, dependencies);
      }
    },
    deps: [ Any, Dependencies ]
]

MyService - provide: MyService, , .

. :

+8

MyService :

import { MyService } from './myservice/index';

{} . , :

import MyService from './myservice/index';

index.ts :

export default MyService;.

TypeScript : https://www.typescriptlang.org/docs/handbook/modules.html

0

Source: https://habr.com/ru/post/1657647/


All Articles