Štěpán Vyhnálek Štěpán Vyhnálek - 1 month ago 39
Ajax Question

angular 2 lazy loading - routes from server

I have been working on an Angular 2 project using lazy loading. It's working well, but what I need is to get the module name from the server and then create a route, but it's not working.

Here is what I have:

import { Routes, RouterModule } from '@angular/router';

function getRoutes(): Routes{
let x: any = [
{path: '', redirectTo: 'welcome', pathMatch: 'full'},
{path: 'backend', loadChildren: 'app/backend/backend.module'}
]
return x;
}

export const routes: Routes = routess();

export const routing = RouterModule.forRoot(routes);


And here is, what do i need:

import { Routes, RouterModule } from '@angular/router';

function getRoutes(): Routes{
let x: any;

$.get( "api/getRoutes", function( data ) {
x = data; //object array from server
});
return x;
}

export const routes: Routes = routess();

export const routing = RouterModule.forRoot(routes);


The problem is, that the function
getRoutes
is not waiting for the server result and returns empty data.

Is there any way to wait for the server data and then add data to the routes?

Answer

Use NgModule just for basic routing setup (/welcome, etc.), then somewhere else in your app load routes and update router configuration. You can then use resetConfig():

this.http.get('/api/getRoutes')
  .subscribe(config => this.router.resetConfig(config))