How to inject different service based on certain build environment in Angular2?

后端 未结 9 1655
醉话见心
醉话见心 2020-12-04 08:50

I have HeroMockService that will return mocked data and HeroService that will call back end service to retrieve heroes from database.

Assum

9条回答
  •  清歌不尽
    2020-12-04 09:22

    A lot of these answers are correct but will fail tree shaking. The mock services will be included as part of the final application which is usually not what is desired. In addition, it isn't easy to switch in and out of mock mode.

    I have created a working example which solves these problems: https://github.com/westonpace/angular-example-mock-services

    1. For each service, create an abstract class or a value token & interface. Create a mock service and a real service which implement the abstract class / interface.
    2. Create a MockModule which provides all of your mock services and a RealModule which provides all of your real services (make sure to use the useClass/provide fields to provide the interface/abstract class)
    3. In the appropriate environment.*.ts files load either the RealModule or the MockModule
    4. Make changes to the angular.json file used by angular-cli to create a new build target mock which builds with the mock environment file which injects the MockModule. Create a new serve configuration which serves up the mock build so you can do ng serve -c mock. Change the default protractor configuration so that it uses the mocked serve target so ng e2e will run against your mock services.

提交回复
热议问题