New Angular2 Router Configuration

Back when using an obsolete router, I was able to execute router.config and pass the object. The fact is that the router itself was slightly configured after the application was launched, the object had the same “template” as if I used @RouterConfig. I am looking for if there is a way to configure a new router in this way. Looking through the documentation, but I do not understand a bit, as it is not yet documented.

Edit due to answer

No, I can not use @Routes. The fact is that I load the configuration after building the router. Here's how I did it with the old router:

myLoader.loadComponentConfig(configPath) .then(components => { self.Components = components; components.map(comp => { self.RouterComponents.push( { path: '/' + comp.name, component: comp, as: comp.name } )}); router.config(self.RouterComponents); }); 

As you can see, I create a json (RouterComponents) object and then send it to the router. I am looking for a way to do the same with a new router or something similar.

+4
source share
3 answers

In the new router ( >= RC.3 ) https://angular.io/docs/ts/latest/api/router/index/Router-class.html resetConfig can be used

 router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ { path: 'simple', component: SimpleCmp }, { path: 'user/:name', component: UserCmp } ] } ]); 

You may need to provide some configuration of an empty router so as not to get errors when starting the application.

https://github.com/angular/angular/issues/11437#issuecomment-245995186 provides RC.6 Plunker

+3
source

I think this is better:

In main.ts:

 import { ROUTER_PROVIDERS } from 'angular2/router'; bootstrap(AppComponent, [ ROUTER_PROVIDERS, provide(LocationStrategy, { useClass: HashLocationStrategy }) ]); 

In your component.ts file:

 import { Router, RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router'; import { APP_ROUTES } from './route.config'; @RouteConfig(APP_ROUTES) 

And create a route.config.ts file:

 import { Route } from 'angular2/router'; import { HomeComponent } from './home/home.component'; import { TableComponent } from './table/table.component'; export var Routes = { home: new Route({ path: '/home', component: HomeComponent, name: 'Home', useAsDefault: true, data: { title: 'Home' } }), table: new Route({ path: '/table/:table', component: TableComponent, name: 'Table' }) }; export const APP_ROUTES = Object.keys(Routes).map(r => Routes[r]); 
0
source

In fact, in short, you need to use @Routes instead of @RouterConfig . Here is an example:

 @Routes([ {path: '/crisis-center', component: CrisisListComponent}, {path: '/heroes', component: HeroListComponent}, {path: '*', component: CrisisListComponent} ]) export class AppComponent { } 

See this angular.io document for more details:

You may notice that some typos remain in this document, as this chapter is under development; -)

-1
source

All Articles