2016-10-14 137 views
4

在Angular 2.0稳定,我有一个应用程序,我必须根据我收到的JSON数据定义/配置路线。我没有任何预定义的路由。我在我的引导组件的构造函数中获取这些数据。Angular 2 - 从JSON数据动态路由

我该如何做到这一点?可能吗?

+0

您可以使用'router.replaceConfig(routes:Routes)',只需根据您的JSON生成路由... – Sasxa

+0

这就是问题所在。那时我没有组件,因为我不知道哪一个是必需的。所以我不能制作像{{path:'Page2',component:Page2}'这样的路线, –

+0

您可以使用'{path:'Page2',loadChildren:“,.module#Page2”}',它只是一个字符串... – Sasxa

回答

2

我实现这一目标的方式是在引导角度应用程序之前加载路线。这种方式,当应用程序启动时,所有的动态路线已经在那里。

因此,您必须在platformBrowserDynamic().bootstrapModule(AppModule);行之前加载main.ts文件中的所有路由。

以下是main.ts文件的示例,其中路径作为json提取并在引导之前加载。

import { enableProdMode } from '@angular/core'; 
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 

import { environment } from './environments/environment'; 
import { AppModule } from './app/app.module'; 
import { IRoute, IRouteData } from './core/models/route'; 
import { getComponent } from './core/utils/type-component-mapper'; 

import { AppRoutes } from './app/app.routes'; 

export function main() { 
    console.log('[main]') 
    return platformBrowserDynamic() 
     .bootstrapModule(AppModule) 
     .catch(err => console.error(err)); 
} 

switch (document.readyState) { 
    case 'interactive': 
    case 'complete': 
     getRoutes(); 
     break; 
    case 'loading': 
    default: 
     document.addEventListener('DOMContentLoaded',() => getRoutes()); 
} 

function getRoutes() { 
    // This is where you load the routes json from your api 
    fetch(environment.apiUrl + '/api/routes/get').then((value: Response) =>       
    { 
     return value.json(); 
    }).then((routes: IRoute[]) => { 
     routes.forEach((o: IRoute) => { 
      iterate(o); 
     }); 

     // add each dynamic route to the angular route collection 
     AppRoutes.unshift(routes[0]); 

     // all dynamic routes have been added, start the angular app 
     main(); 
    }); 
} 

function iterate(route: IRoute) { 
    var children = route.children; 
    if (children) { 
     Array.from(children).forEach((o: IRoute) => { 
      iterate(o) 
     }); 
    } 

    var component = getComponent(route.data.type); 
    if (component) { 
      route.component = component; 
    } 
} 

在该示例中,其是从所述API返回的路由JSON将是这种形式:

[{ 
    "path" : Shop, 
    "data" : { 
     "type" : ShopPage 
    }, 
    "children" : [{ 
     "path" : Bread, 
     "data" : { 
      "type" : ProductPage 
     } 
    }, 
    { 
     "path" : Milk, 
     "data" : { 
      "type" : ProductPage 
     } 
    }] 
}] 

此JSON数据解析为IRoute和IRouteData类型:

export interface IRoute { 
    path: string; 
    data: IRouteData; 
    children?: IRoute[]; 
} 

export interface IRouteData { 
    type: string; 
} 

导出您的AppRoutes常量也很重要,以便您可以将新的动态路由推送到您的AppRoutes集合。它看起来像这样:

export const AppRoutes: Routes = [ 
    { 
     path: 'hardCodedWelcome', 
     component: WelcomeComponent 
    } 
]; 

您还需要为每个路由添加正确的组件。在这种情况下,我会切换数据类型属性以获取正确的组件。这就是为什么我从类型组件映射文件,它看起来像这样导入GET组件功能:

import { Router, Route } from '@angular/router'; 

import { Type } from '@angular/core'; 
import { PageTypes } from './page-types'; 
import { ShopComponent } from '../../app/Shop/shop.component'; 
import { ProductComponent } from '../../app/Product/Product.component'; 

export function getComponent(type: string): Type<any> { 
    switch (type) { 
     case PageTypes.Shop: { 
      return ShopComponent; 
     } 
     case PageTypes.Product: { 
      return ProductComponent; 
     } 
    } 
} 

页这里类型是网页类型的只是一个简单的列表,所以我没有使用魔法字符串。

export const PageTypes = { 
    Shop: 'ShopPage', 
    Product: 'ProductPage', 
}; 

当应用程序启动时,所有动态路由都存在于路由集合中,并且可以通过角度来正常解析。这会为应用程序增加一些启动时间,具体取决于有多少路线。但是,一旦应用程序启动,所有路由都在配置路由集合中,并且不会对性能产生进一步的影响。