如何在Angular 2中有条件地加载模块 [英] How to load modules conditionally in Angular 2

查看:67
本文介绍了如何在Angular 2中有条件地加载模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码可以根据不同的Angular-cli环境变量有条件地加载模拟服务.但是,这样做的副作用是,将模拟服务内置到最终的经过转码和最小化的输出文件中.

The code below can conditionally load a mock service based on different Angular-cli environment variables. However it has a side effect that the mock services get built into the final transcoded and minified output files.

是否有更好的方法在angular2中完成延迟加载模块?

Is there a better way to accomplish lazy loading modules in angular2?

app.module.ts:

app.module.ts:

import {BrowserModule} from "@angular/platform-browser";
import {NgModule} from "@angular/core";
import {FormsModule} from "@angular/forms";
import {HttpModule} from "@angular/http";
import {AppComponent} from "./app.component";
import {environment} from "../environments/environment";
import {XService} from "./xxx.service";
import {XMockService} from "./xxx-mock.service";

let importedModules: Array<any> = [
  XService
];

if (environment.mock) {
  importedModules.push(
    {provide: XService, useClass: XMockService}
  );
} else {
  importedModules.push(
    XService
  );
}

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: importedModules,
  bootstrap: [AppComponent]
})

export class AppModule {}

推荐答案

您可以尝试类似的操作.

You might try something similar to this.

main.ts

platformBrowserDynamic().bootstrapModule(RootModule);

root.module.ts

@NgModule({
  imports: [
    LandingModule,
    UserModule
  ],
  entryComponents: [PageComponent, UserComponent],
})
export class RootModule {

  constructor(private router: Router .....) {
  }

  ngDoBootstrap(ref: ApplicationRef) {
    const isUserPageRequested = this.shouldGoToUser();
    if (isUserPageRequested) {
      this.router.resetConfig(userRoutes);
      ref.bootstrap(UserComponent);
    } else {
      ref.bootstrap(PageComponent);
    }
  }
}

PageComponent LandingModule 中声明, UserComponent UserModule 中声明.这样,可以在使用aot编译时在模块正常工作时有条件地加载模块.

PageComponent is declared in LandingModule and UserComponent is declared in UserModule. This way it is possible to conditionally load module while it works when compiled with aot.

这篇关于如何在Angular 2中有条件地加载模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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