Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

typescript - angular-cli: Conditional Imports using an environment variable

Is there a way to conditionally change imports based on an environment variable in angular-cli@1.0.0-beta.16? I'm trying to do it in a way that doesn't require code changes in how services are imported in client code, but when needed I can specify a build flag to swap in mock services.

There is a pattern I tried using 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 can see the dependency getting injected when stepping through the code, however there are compilation errors (which I believe are TypeScript errors) along the lines of Cannot find name 'MyService'.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're going about it completely wrong. Angular can handle this use case with the use of factories when you configure the 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 ]
]

Now you can just inject MyService everywhere because of the provide: MyService, but in development, you will get the mock, and in production you will get the real service.

See Also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...