gpt4 book ai didi

angular-cli:使用环境变量的条件导入

转载 作者:太空狗 更新时间:2023-10-29 17:13:58 26 4
gpt4 key购买 nike

有没有办法根据 angular-cli@1.0.0-beta.16 中的环境变量有条件地更改导入?我正在尝试以一种不需要更改客户端代码中服务导入方式的代码的方式来执行此操作,但在需要时我可以指定构建标志以交换模拟服务。

我尝试使用 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';

页面加载,我可以看到在逐步执行代码时注入(inject)了依赖项,但是存在编译错误(我认为是 TypeScript 错误),如 Cannot find name 'MyService'.

最佳答案

你的做法完全错了。当您配置 providers

时,Angular 可以使用 工厂来处理这个用例
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 ]
]

现在,由于 provide: MyService,您可以在任何地方注入(inject) MyService,但在开发中,您将获得模拟,而在生产中,您将获得真正的服务.

另请参阅:

关于angular-cli:使用环境变量的条件导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40027892/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com