3

I am trying to load the routes from a JSON file, as i do not want to hard code them and load the routes lazily. Something like this:

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);
I want to load the following routes from a JSON file.

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

I am reading the JSON file using a service which is injected in a component. How do i inject the service in the router to get the values? Or is there any other better way using which i can load the routes from JSON?

1
  • did u found solution for this ? Commented Feb 2, 2017 at 13:06

1 Answer 1

1

This works for me:

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

    }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.