angular-cli:使用环境变量的条件导入 [英] angular-cli: Conditional Imports using an environment variable
问题描述
有没有办法根据 angular-cli@1.0.0-beta.16 中的环境变量有条件地更改导入?我正在尝试以一种不需要更改客户端代码中服务导入方式的方式来实现,但在需要时我可以指定一个构建标志来交换模拟服务.
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:
文件结构:
MyService
MyServiceMock.ts
MyServiceReal.ts
index.ts
在你的 index.ts 中,你可以有以下内容:
import { environment} from '../environments/environment';
export const MyService = environment.mock ?
require('./MyServiceMock').MyServiceMock:
require('./MyServiceReal').MyServiceReal;
在您的客户端代码中,导入 MyService:
import MyService from './myservice/index';
页面加载,我可以看到在单步执行代码时注入了依赖项,但是在 Cannot find name 'MyService'
.
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'
.
推荐答案
你的做法完全错误.当你配置 providers
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 ]
]
现在你可以在任何地方注入 MyService
因为 provide: MyService
,但是在开发中,你会得到模拟,而在生产中你会得到真正的服务.
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.
另见:
这篇关于angular-cli:使用环境变量的条件导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!