简体   繁体   English

Angular2注入器-动态选择服务实现

[英]Angular2 Injector - Dynamically choose Service Implementation

For better testing and separating frontend / backend development we are currently trying to find a dynamic way to provide mock service implementations in devMode. 为了更好地测试和分离前端/后端开发,我们目前正在尝试寻找一种动态方式来提供devMode中的模拟服务实现。

The idea is to specify in your environment which services shall be mocked and have the injector then return either the real or the mocked implementation based on this. 这个想法是在您的环境中指定将模拟哪些服务,然后让注入程序根据此结果返回真实的或模拟的实现。

The question is now if it is possible to dynamically do this for every service the injector provides or if we have to use a separate factory (doing the same thing) for every service? 现在的问题是,是否有可能为喷油器提供的每项服务动态地执行此操作,或者我们是否必须为每项服务使用单独的工厂(做同样的事情)?

// pseudo code
onRequestProviderFor(serviceName)
{
  if(environment.mockTheseServices.contains(serviceName))
  {
    return new "Mock"+serviceName.ts
  }
  else
  {
    return new serviceName.ts
  }
}

Is this possible? 这可能吗? And is there a hook in the injector process we could use to do this (in devMode)? 在注入器过程中是否可以使用钩子(在devMode中)?

Did you consider creating a separate mock server using something like https://github.com/typicode/json-server ? 您是否考虑过使用https://github.com/typicode/json-server之类的东西来创建单独的模拟服务器?

I think it would keep your project code cleaner to not include mock services in the same code base. 我认为这将使您的项目代码更整洁,不将模拟服务包含在同一代码库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM