angular2 router in service?

2.1k Views Asked by At

I'm building an app with angular2 alpha27 and systemjs. It's supposed to be a big app one day and many components are supposed to use links inside the app. For the moment, to determine the router config I put this into app.ts:

@RouteConfig([
    { path: '/', as: 'overview', component: Overview },
    { path: '/requests', as: 'requests', component: Requests },
    { path: '/pane', as: 'pane', component: Pane }
])

The problem:

If I need in other components to put a link to Overview like this <a router-link="overview">Overview</a> I have to import to that component all router injectables and define RouterConfig and import components (like Overview, Pane, etc.. mentioned above) to make linking work.

First, it doesn't make any sense to import all these to several components that only need a link to Overview, for example.

Second, I would like to define my @RouterConfig only once for maintenance reasons.

The idea I have is to make a service, that would define @RouterConfig and make it available to any component. But I have no idea, how to do this.

Please, would anyone have an idea of the best way of arranging such code?

2

There are 2 best solutions below

2
On BEST ANSWER

No, you'll only need to use @RouterConfig once like you suggest in the main app component. To link from one component to another you need to import RouterLink and pass as directive to the View-annotation.

import { RouterLink } from 'angular2/router'

@Component({ selector: 'foo' })
@View({
  template: `<a [router-link]=['/bar']>Link to bar</a>`,
  directives: [RouterLink])
export class FooComponent {
}

I've done a video tutorial on angular 2 routing if you're interested, make sure to check it out https://youtu.be/ZsGRiHSaOxM

2
On

Extensibility shouldn't be a problem.

With the new-angular-router you attach your route config to a class/controller, rather than a service. This way is actually a lot more flexible, as you can even have apps within apps within apps, all with their own routes.

Think of it like a tree, and any branch of the tree can start adding more branches anytime, wherever they need to go. Those new branches stem off of each other.

If routes are defined in one place rather than when needed your code will become much less modular than if you were to attach routes to components, which can then be moved around without breaking, paralleling the file structure.

My advice: think in trees as perhaps nature intended. This advice of course does not suit all use cases, but is the simplest course of action.