flyingMonkeys
flyingMonkeys

Reputation: 235

How can I have an external JSON data file with my route parameters in Angular2?

I am new to Angular, and obviously Angular 2 also. I'm trying to store my route parameters in an external file (ex., a JSON formatted data file).

The closest I've come to getting it to work is to create a .js file with a variable set to my route parameters, and include it.

var routeParams = [
        { path: '/',             as: 'Home',          component: HomeComponent },
        { path: '/petlist',      as: 'Petlist',       component: PetlistComponent }
    ];

Then use it for the RouteConfig:

@RouteConfig(routeParams)

But the problem is that the it is expecting the components to be classes, and they don't exist in the .js file.

I also tried having a function that returns the JSON route parameters, but I have the same issue with the component classes.

The system I am working with already has a UI for the user to create web pages, setup menus, etc. I am trying to have that system output Bootstrap/Angular2 templates. Because the user can create their own web pages I'm not sure how to setup the routes since they can change. I thought using a JSON data file would be a good solution, but my app obviously needs to use the route data from that file instead of being hard-coded in the app.

I am using Angular 2.0.0-beta.0 and TypeScript.

Upvotes: 0

Views: 1882

Answers (2)

Vitor Paixão
Vitor Paixão

Reputation: 25

You can do this with resetConfig() , getting the data from server then reading actual router data with router.config in another array, and pushing the new routes.

addRouteConfig(): void {
    const allRoute = this.router.config;
    allRoute.push(
        {
            path: 'someroute',
            component: someRouterComponent
        }
    );
    this.router.resetConfig(allRoute);
}

Upvotes: 0

Murhaf Sousli
Murhaf Sousli

Reputation: 13306

It would be great if its possible in angular2, unfortunately, You won't find any example like that in the routing docs, you must manually define the component class for each route. however you can loop over multiple routes sharing the same component. (ex: bookmarks)

Upvotes: 0

Related Questions