角度2延迟加载-来自服务器的路由 [英] angular 2 lazy loading - routes from server

查看:38
本文介绍了角度2延迟加载-来自服务器的路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用延迟加载进行Angular 2项目.它工作正常,但是我需要从服务器获取模块名称,然后创建路由,但是它不起作用.

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.

这就是我所拥有的:

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

这是我需要的:

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

问题在于,函数 getRoutes 没有等待服务器结果并返回空数据.

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?

推荐答案

仅将 NgModule 用于基本路由设置(/welcome 等),然后将其用于其他地方您的应用加载路线并更新路由器配置.然后,您可以使用 resetConfig() :

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

这篇关于角度2延迟加载-来自服务器的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆