【问题标题】:Angular2 rc1 - Is order of @Routes declaration important (optional parameter)?Angular2 rc1 - @Routes 声明的顺序是否重要(可选参数)?
【发布时间】:2016-10-05 04:52:57
【问题描述】:

尝试新的 Angular 2.0.0-rc.1 没有过时的东西。 我希望一个组件可以使用或不使用路径参数。由于我无法弄清楚可选参数的语法(例如/detail/:id?/detail[/:id] 不起作用),我只能选择声明单独的路由。根据我声明@Routes 的顺序,我遇到了异常

为什么这么好:

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

这不是:

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

访问参数化 url 时:localhost/detail/1 出现异常:

异常:错误:未捕获(承诺中):组件 'HeroDetailComponent' 没有路由配置

组件类供参考:

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);
  }
}

【问题讨论】:

    标签: angularjs typescript angular angular-ui-router


    【解决方案1】:

    是的,顺序很重要。更具体的路线应该放在第一位,不太具体的路线最后。

    这不是故意的,而是当前@angular/router 的限制。

    目前尚不清楚他们将如何与路由器一起前进。如果您刚开始从 @angular/router-deprecated 迁移,最好等到路由器策略明确。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-23
      • 2010-10-22
      • 1970-01-01
      • 2019-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-22
      相关资源
      最近更新 更多