0

I want to build a generic module that I can pass some config to customize it. For example, in the root module I want to have something like

@NgModule({
    imports: [
        moduleFactory(config1),
        moduleFactory(config2),
        moduleFactory(config3)
    ],
})
export class AppModule { }

The moduleFactory will return a module with routes that will be constructed based on configx objects. These modules will provide some views that will show customized content based on the config object. How can I do that?

csbenjamin
  • 356
  • 2
  • 8
  • there's a way to do that using `ModuleWithProviders`, but if you put some logic that requires runtime execution into `moduleFactory`, it won't work with AOT – Max Koretskyi Nov 30 '17 at 06:44
  • @AngularInDepth.com The main problem I am having is just with AOT. Now I have only the main `NgModule` defining the routes, and in the route config array I call a function that returns a route object config and when I run `ng serve` I got an error: Error encountered resolving symbol values statically. Calling function 'admin', function calls are not supported. Is it worth giving up AOT to have less code? I don't understand AOT very well and I don't know the benefits to use it. – csbenjamin Nov 30 '17 at 09:25
  • yeah, that's expected, static analysis doesn't evaluate the code. No, it's not worth giving up AOT. The compiler takes around 40% of the Angular code that you ship to a browser which is not shipped with AOT and with pre-compiled components you also get startup time boost – Max Koretskyi Nov 30 '17 at 17:52
  • Thanks for taking your time – csbenjamin Nov 30 '17 at 18:15
  • sure, good luck) check out [angularindepth](https://blog.angularindepth.com/) publication, there's a wealth of in-depth information there – Max Koretskyi Nov 30 '17 at 18:18
  • @AngularInDepth.com I came up with a solution and posted as an answer – csbenjamin Nov 30 '17 at 23:34

1 Answers1

0

I came up with a solution using loadChildren. In the main route config I have something like this:

{
    path:'companies',
    loadChildren: 'app/admin/admin.module#AdminModule',
    data:{
        // the config1
    }
},

{
    path:'users',
    loadChildren: 'app/admin/admin.module#AdminModule',
    data:{
        // the config2
    }
}

Then, in the AdminModule I can read the data property. Besides, I was trying to define absolute route paths in AdminModule routes, but now, with the loadChildren solution, I can define relative paths, therefore I can have the routes defined statically and AOT just works :). I have something like this in the AdminModule routes:

{
    path: '',
    component: TablePageComponent,
},
{
    path: 'item',
    component: FormPageComponent,
}

With that, I can load the users table with the route /users and a specific user with the route /users/item;id=1. The same applies to the companies and whatever else.

csbenjamin
  • 356
  • 2
  • 8