在Angular2中通过JSON加载路由

时间:2016-11-03 15:23:21

标签: angular angular2-routing angular2-router

我正在尝试从JSON文件加载路由,因为我不想对它们进行硬编码并且懒洋洋地加载路由。 像这样:



import { RouterModule } from '@angular/router';
const routes = [
    { path: '', loadChildren: 'app/home/home.module' },
    { path: ':item/shoes', loadChildren: 'app/shoes/shoes.module' },
    { path: ':item/watch', loadChildren: 'app/watch/watch.module' }
];
export default RouterModule.forRoot(routes);



 我想从JSON文件加载以下路由。



{ path: '', loadChildren: 'app/home/home.module' },
        { path: ':item/shoes', loadChildren: 'app/shoes/shoes.module' },
        { path: ':item/watch', loadChildren: 'app/watch/watch.module' }




我正在使用注入组件的服务来读取JSON文件。如何在路由器中注入服务以获取值?或者还有其他更好的方法可以从JSON加载路由吗?

1 个答案:

答案 0 :(得分:1)

这对我有用:

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

    }

}