How to load modules conditionally in Angular 2

后端 未结 1 381
一生所求
一生所求 2021-02-04 11:57

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

相关标签:
1条回答
  • 2021-02-04 12:50

    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 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.

    0 讨论(0)
提交回复
热议问题