JockX JockX - 6 months ago 63
AngularJS Question

Angular2 rc1 - Is order of @Routes declaration important (optional parameter)?

Trying out the new Angular 2.0.0-rc.1 without the depracated stuff.
I want a component to work with or without path parameter. As I was unable to figure out the syntax for optional paramter (eg.

/detail/:id?
or
/detail[/:id]
would not work) I was left with the option to declare separate routes. Depending on the order I declare the @Routes, I'm hitting an exception

Why is this good:

@Routes([
{ component: HeroDetailComponent, path: '/detail/:id' },
{ component: HeroDetailComponent, path: '/detail' }
])


and this is not:

@Routes([
{ component: HeroDetailComponent, path: '/detail' },
{ component: HeroDetailComponent, path: '/detail/:id' }
])


When accessing parametrized url:
localhost/detail/1
I get an exception:


EXCEPTION: Error: Uncaught (in promise): Component
'HeroDetailComponent' does not have route configuration


Component class for reference:

import {OnActivate, RouteSegment, Router} from "@angular/router";
import {Component, Input} from '@angular/core';
import {Hero} from '../model/hero';
import {HeroService} from "../model/hero.service";

@Component({
templateUrl: 'hero-detail.component.html',
selector: 'my-hero-detail'
})

export class HeroDetailComponent implements OnActivate{
constructor(private heroService: HeroService,
private router: Router){}
@Input()
hero: Hero = new Hero();

routerOnActivate(curr: RouteSegment) {
if(curr.getParam('id') == null)
return;

let id = +curr.getParam('id');
this.heroService.get(id)
.then(hero => this.hero = hero);
}
}

Answer

Yes, the order is important. More specific routes should come first, less specific ones last.

This is not intentional but a limitation of the current @angular/router.

It's currently not clear how they will move forward with the router. If you're just starting migrating from @angular/router-deprecated it's probably better to wait until the router strategy is made clear.