简体   繁体   中英

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.

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)?

Did you consider creating a separate mock server using something like 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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