Angular Dynamic Routing and Lazy loading

377 views
Skip to first unread message

Sukesh Marla

unread,
Jul 6, 2018, 12:29:25 PM7/6/18
to Angular and AngularJS discussion

I am trying to create my Angular routes dynamically from Database. I somehow achieved it.

I followed AppIntializer for same.

App.module.ts ....


providers:[...{
        provide: APP_INITIALIZER,
        useFactory: AppInitializerFn,
        multi: true,
        deps: [AppConfigService,RouteConfigService]
      }...]


  export const AppInitializerFn = (
    appConfig: AppConfigService,
    routeConfigService:RouteConfigService) => {
    return () => {
      return appConfig.loadAppConfig().then(()=>{
        return  routeConfigService.configure();
      });
    };
  };

 configure() {
    appRoutes[1].children= [];
    return this.http.get('/assets/data/menu.json').toPromise()
    .then((data:Array<any>) => {

      data.forEach((x:any)=>{
        appRoutes[1].children.push({path:x.path,
          loadChildren: this.appConfig.getConfig().AppSpecificComponentURL+x.compPath
        });

      });

      var router: Router = this.injector.get(Router);
      router.resetConfig(appRoutes);
      console.log(appRoutes)
    });
  }

menu.json

[
          { "path": "dashboard", "compPath":"dashboard/dashboard.module#DashboardModule","default":true},
          { "path": "customer", "compPath":"customer/customer.module#CustomerModule"},
          { "path": "employee", "compPath":"employee/employee.module#EmployeeModule"},
          { "path": "supplier", "compPath":"supplier/supplier.module#SupplierModule"}
    ]


Now the problem is Lazy loaded modules are not even compiling and so getting an error "Cannot find module "./src/app/app-specific/employee/employee.module"

Any help appreciated.

Sander Elias

unread,
Jul 8, 2018, 2:01:08 AM7/8/18
to Angular and AngularJS discussion
Hi Sukesh,

AppIntializer is executed before anything else. This means you can't really use the injector or anything else from within your application that is not pure. (there are many edge cases around this moment, you can dig in if you really want to know).
To make a long story short, don't use anything angular in your initialization, and you should be good. Use fetch instead of HTTP. Make sure you load the stuff you need and kick off initialization of the routes from your appComponent. This can be done by injecting a service that uses the data you just set up in appIntializer.

Regards
Sander
Reply all
Reply to author
Forward
0 new messages