angular 2 lazy loading - routes from server

∥☆過路亽.° 提交于 2019-12-24 08:25:06

问题


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?


回答1:


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))


来源:https://stackoverflow.com/questions/39982936/angular-2-lazy-loading-routes-from-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!