禁用angular2 in-memory-web-api进行生产

Ema*_*ger 9 angular

我正在使用angular2 in-memory-web-api进行开发.对于生产环境,我想禁用in-memory-web-api和我要使用的真实API.有没有办法禁用InMemoryWebApiModule生产?

Dam*_*ian 7

这种简单的方法对我有用:

const ENV = 'prod'; // your global ENV variable;
-----

@NgModule({
  imports: [
    ...
    HttpModule,
    ENV !== 'prod' ? InMemoryWebApiModule.forRoot(DataMockService) : [],
  ],
  ...
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)


Pau*_*tha 5

假设您有某种"切换",无论是environment节点ENV 的Angular CLI ,您都可以切换XHRBackend应该使用的.在in-memory-web-api使用自己的后端InMemoryBackendService.所以你可以做点什么

import { NgModule, Injector } from '@angular/core';
import { HttpModule, XHRBackend, BrowserXhr,
         ResponseOptions,  XSRFStrategy } from '@angular/http';

import { InMemoryBackendService, InMemoryDbService } from 'angular-in-memory-web-api';

let environment = {
  production: true
};

export class MockData implements InMemoryDbService {
  createDb() {
    let cats = [
      { id: 1, name: 'Fluffy' }
    ];
    return { cats };
  }
}

@NgModule({
  imports: [ HttpModule ],
  providers: [
    {
      provide: XHRBackend,
      useFactory: (injector: Injector, browser: BrowserXhr,
                   xsrf: XSRFStrategy, options: ResponseOptions): any => {
        if (environment.production) {
          return new XHRBackend(browser, options, xsrf);
        } else {
          return new InMemoryBackendService(injector, new MockData(), {
            // the configuration object
          });
        }
      },
      deps: [ Injector, BrowserXhr, XSRFStrategy, ResponseOptions ]
    }
  ]
})
export class AppHttpModule {
}
Run Code Online (Sandbox Code Playgroud)

在这里,我们导入HttpModule,然后XHRBackend动态创建依赖.在开发环境中,它将使用后端服务,这实际上是在我们使用时发生的事情InMemoryWebApiModule.因此,我们不是使用该模块,而是自己配置后端服务.在生产环境中,它只使用XHRBackend通常使用的相同内容.

还要注意environment.这只是一个例子.这可能不会被您使用.理想情况下,环境应该是在命令行上控制的.使用Angular CLI,它实际上确实提供了一个environment变量environment/environment.环境在生产版本中通过CLI自动切换.

如果您没有使用CLI,那么您可能会使用节点ENV或您计划切换生产的任何方式.关键是,environment上面使用的只是一个例子.理想情况下,这不是您想要手动更改的内容.您的项目应该有一些方法来确定生产构建,并且应该能够在您的代码中访问.

还有上面的内容AppHttpModule,你不再需要导入HttpModule到你的AppModule,只需导入即可AppHttpModule