Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate angular 2 route config from main app file

I want to separate route config from app file into different file like (routeConfig.ts). It is possible?

For example:

import {Component} from 'angular2/core';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {DashboardComponent} from './dashboard/dashboard.component';


import {MessagesComponent} from '../modules/messages/messages.component';


@Component({
    selector: 'app',
    directives: [
      ROUTER_DIRECTIVES
    ],
    templateUrl: './built/application/app.html'
})

@RouteConfig([
  {
    path: '/',
    name: 'Dashboard',
    component: DashboardComponent,
    useAsDefault: true
  }
])

export class AppComponent {}

I want to move @RouteConfig params into different file and just load it inside main app file. It is possible? Thanks. (Route config wil be wery big, so I want to split this).

First trouble, it is that when I try to move config into different file and just try to import JSON in app file - I got errors with Undefined Component. Because componentsName its not a string. Cant solve this issue.

like image 346
Velidan Avatar asked Mar 30 '16 12:03

Velidan


1 Answers

You can certainly move all the route definitions into a separate file.

In a file like route-definitions.ts:

import { RouteDefinition } from 'angular2/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { InfoComponent } from './info/info.component';

export const RouteDefinitions: RouteDefinition[] = [
    {
        path: '/',
        name: 'Home',
        component: HomeComponent,
        useAsDefault: true
    },
    {
        path: '/about',
        name: 'About',
        component: AboutComponent
    },
    {
        path: '/info',
        name: 'Info',
        component: InfoComponent
    }
];

Then back in your app.component.ts file just do:

import { Component } from 'angular2/core';
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router';
import { RouteDefinitions } from './route-definitions';

@Component({
    selector: 'my-app',
    templateUrl: 'app/app.component.html',
    directives: [ROUTER_DIRECTIVES],
    providers: [
      ROUTER_PROVIDERS
    ]
})
@RouteConfig(RouteDefinitions)
export class AppComponent { }
like image 164
Rob Louie Avatar answered Oct 09 '22 07:10

Rob Louie