在Angular2中通过JSON加载路由

在Angular2中通过JSON加载路由,angular,angular2-routing,angular2-router,Angular,Angular2 Routing,Angular2 Router,我正在尝试从JSON文件加载路由,因为我不想硬编码它们,而懒散地加载路由。 大概是这样的: 从'@angular/router'导入{RouterModule}; 常数路由=[ {path:'',loadChildren:'app/home/home.module'}, {路径:':item/shoes',loadChildren:'app/shoes/shoes.module'}, {路径:':item/watch',loadChildren:'app/watch/watch.module'

我正在尝试从JSON文件加载路由,因为我不想硬编码它们,而懒散地加载路由。 大概是这样的:

从'@angular/router'导入{RouterModule};
常数路由=[
{path:'',loadChildren:'app/home/home.module'},
{路径:':item/shoes',loadChildren:'app/shoes/shoes.module'},
{路径:':item/watch',loadChildren:'app/watch/watch.module'}
];
导出默认RouterModule.forRoot(路由)这对我很有用:

app-routing.module.ts

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

import * as AppRoutingJson  from "./app-routing.json";

import { HomeComponent } from "./main/content/pages/joomla/home/home.component";
import { PageNotFoundComponent } from "./main/content/pages/joomla/page-not-found/page-not-found.component";

const routes: Routes = [
    {
        path: '',
        component  : HomeComponent
    }
];

@NgModule({
    imports: [ RouterModule.forRoot(routes) ],
    exports: [ RouterModule ],
    entryComponents: [
        PageNotFoundComponent
    ]
})

export class AppRoutingModule {

    constructor( private router: Router ){

        this.prepareRoutes( AppRoutingJson );

    }

    prepareRoutes( routesJson: any ) {

        let routesArr = <Routes>[];

        routesArr = routesJson;

        routesArr.forEach( route => {

            routes.push( route );

        });

        routes.push(
            {
                "path"      : 'page-not-found',
                "component" : PageNotFoundComponent,
            },
            {
                "path"       : '**',
                "redirectTo" : 'page-not-found'
            }                           
        );

        this.router.resetConfig( routes );  

    }

}
从'@angular/core'导入{NgModule};
从'@angular/Router'导入{RouterModule,Routes,Router};
从“/app routing.json”以批准的方式导入*;
从“/main/content/pages/joomla/home/home.component”导入{HomeComponent}”;
从“/main/content/pages/joomla/page not found/page not found.component”导入{PageNotFoundComponent}”;
常数路由:路由=[
{
路径:“”,
组件:HomeComponent
}
];
@NGD模块({
导入:[RouterModule.forRoot(路由)],
导出:[路由模块],
入口组件:[
PageNotFoundComponent
]
})
导出类批准模块{
构造函数(专用路由器:路由器){
本文件编制(批准);
}
prepareRoutes(路由JSON:any){
设RouteSar=[];
RouteSAR=routesJson;
routesArr.forEach(route=>{
路线。推(路线);
});
推(
{
“路径”:“未找到页面”,
“组件”:PageNotFoundComponent,
},
{
“路径”:“**”,
“重定向到”:“未找到页面”
}                           
);
this.router.resetConfig(路由);
}
}

您找到解决方案了吗?