Search code examples
angularangular2-routing

How to dynamically compose a route in angular?


Let's suppose I have a service that fetches an array of paths formatted in json like this:

[{
    "path": "routeName"
    "component": "MyComponent"
}]

Of coures "MyComponent" is retrieved as a string. Now I want translate this array into Routes for a routing-module. How can I convert "MyComponent" into the class MyComponent?

The purpose of this is to make my frontend unaware of what it is. To add new routes and components I just need to add a new entry to the file on the server and make it match the component name I create inside the angular app.


Solution

  • Here is app module

    export const routes: Route[] = [
    
    ];
    @NgModule({
      declarations: [
        AppComponent,
        ErrorHandleComponent,
        FilterComponent,
        CreateComponent
      ],
      imports: [
        BrowserModule,
        RouterModule.forRoot(routes),
        // AppRoutingModule,
        HttpClientModule
      ],
      entryComponents: [
        CreateComponent,
        FilterComponent,
        ErrorHandleComponent
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    Now make sure that you have the key value pair obj that returns component against key like:

    import { CreateComponent } from '../create/create.component';
    import { FilterComponent } from '../filter/filter.component';
    import { ErrorHandleComponent } from '../error-handle/error-handle.component';
    
    export const components = {
        'CreateComponent': CreateComponent,
        'FilterComponent': FilterComponent,
        'ErrorHandleComponent': ErrorHandleComponent,
    };
    

    Then put this code in app.component.ts file

      constructor(private api: ApiService, private router: Router) {
    
      }
      getRoute() {
        this.api.get_route().subscribe(res => {
          res.forEach(element => {
             // components key value pair obj
             element.component = components[element.component]; 
            routes.push(element);
          });
          this.rlist = routes;
          this.router.resetConfig(routes);
        });