angular-cli:使用环境变量进行条件导入 [英] angular-cli: Conditional Imports using an environment variable

查看:125
本文介绍了angular-cli:使用环境变量进行条件导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以根据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.

我尝试从这篇文章中尝试使用的模式:

文件结构:

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'的代码行中存在编译错误(我认为是TypeScript错误).

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 ]
]

现在,由于provide: MyService,您可以随处注入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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆