Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add additional Routes dynamically in Angular

I'm using Angular 5.2.2 (typescript) with Angular-CLI and .NET Core 2.0.

I'm trying to add additional Routes dynamically to my application.

The idea is that I get my routes dynamically from a server which checks what modules should be available to the user. But I cant seem to get the routes to become available.

I've tried to add them using RouterModule.forRoot but that did not work.

I've tried using Router.resetConfig but I can't seem to get that working. I try to use dependency injection to get it in the function I've created but I end up with a cyclic dependency:

Uncaught Error: Provider parse errors:
Cannot instantiate cyclic dependency! ApplicationRef ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1

Here is a bit of the code I have:

app-routing.module.ts

import { NgModule, APP_INITIALIZER } from '@angular/core';
import { Routes, RouterModule, Router } from '@angular/router';

var routes: Routes = [{ path: '', loadChildren: "../app/modules/f2p-dashboard/f2p-dashboard.module#F2PDashboardModule" }];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: AppConfigServiceFactory,
      deps: [F2PModuleService, Router ],
      multi: true
    }
  ]
})

export function AppConfigServiceFactory(moduleService: F2PModuleService, 
router:Router) {
  return () => {
    return moduleService.Init().subscribe((result) => {
      let additionalRoutes = moduleService.GetRoutes()
      routes = routes.concat(additionalRoutes);
      console.log(routes);
      //routes is filled
  router.resetConfig(routes);
  //RouterModule.forRoot(routes);
});

edit: All the routes I'm trying to add make use of loadChildren

like image 535
D. Berg Avatar asked Feb 06 '18 09:02

D. Berg


1 Answers

One of the ways to do this is by pushing the route into the router and using resetConfig.

Example :
constructor(private router: Router, private route: ActivatedRoute) {}
   const config = this.router.config;
   config.push({
            path: 'dynamicRoutePath',
            component: DynamicRouteComponent,
        });
        this.router.resetConfig(config);
        this.router.navigate(['dynamicRoutePath'], {relativeTo: this.route});

This should work.

like image 79
Abhijith Avatar answered Nov 12 '22 09:11

Abhijith