为什么这条带有参数的路由在 Angular2 中不起作用?

Why won't this route with params work in Angular2?

我正在尝试使用参数在 Angular2 中工作的简单路线。我正在使用 Angular 2.0.0-rc.2 和 angular 路由器 3.0.0-alpha.7 .我拥有的大部分内容直接基于路由 https://angular.io/docs/ts/latest/guide/router.html

的更新文档

index.html

<!doctype html>
  <html>
    <head>
      <base href=".">
      ...

main.ts

import { bootstrap } from '@angular/platform-browser-dynamic';
import { AppComponent } from './app';
import { HTTP_PROVIDERS } from '@angular/http';
import { APP_ROUTER_PROVIDERS } from './app/app.routes';

bootstrap(AppComponent, [
    HTTP_PROVIDERS,
    APP_ROUTER_PROVIDERS
])
    .catch(err => console.error(err))
;

app.routes.ts

export const routes: RouterConfig = [
    { path: 'featured',       component: FeaturedPageComponent },
    { path: 'containers/:id', component: ContainerEditComponent }
];

export const APP_ROUTER_PROVIDERS = [
    provideRouter(routes)
];

容器-edit.component.ts

@Component({
    moduleId: module.id,
    selector: 'container-edit',
    templateUrl: 'container-edit.component.html',
    styleUrls: ['container-edit.component.css']
})
export class ContainerEditComponent implements OnInit, OnDestroy {
    private sub: any;

    constructor(
        private route: ActivatedRoute,
        private router: Router
    ) {
    }

    ngOnInit() {
        this.sub = this.route.params.subscribe(params => {
            let id = +params['id']; // + converts string to number
            console.log(id);
        });
    }

    ngOnDestroy() {
        this.sub.unsubscribe();
    }
}

当我点击 http://localhost:4200/containers/1337 时,出现以下错误。

EXCEPTION: Error: Uncaught (in promise): Error: Cannot match any routes: '1337'

更新答案:

在 index.html 中将你的基地设置为 <base href="/" />。 angular2 文档促使您使用 <base href="." />,因为在他们的英雄项目中,他们特别使用 router.navigate,这很好,因为它迫使您从默认路由开始,然后从那里开始创建历史记录。

但在某些情况下,如果您希望用户能够直接前往特定路径,则您必须使用 /

原答案:

检查一下你的路径,你是故意改的吗?示例不包含 'app' 子文件夹。

import { AppComponent } from './app/'; <--- check this
import { HTTP_PROVIDERS } from '@angular/http';
import { APP_ROUTER_PROVIDERS } from './app/app.routes'; <--- and this