7

应用组件

import { Component } from '@angular/core';
import {Router, ROUTER_DIRECTIVES, Routes, ROUTER_PROVIDERS} from '@angular/router';
import {SchoolyearsComponent} from "./schoolyear/schoolyears.component";

@Component({
  directives: [ROUTER_DIRECTIVES],
  providers: [
    ROUTER_PROVIDERS
  ],
  templateUrl: './app/application.component.html',
  styleUrls: ['./app/application.component.css']
})
@Routes([
  {
    path: '/',
    component: SchoolyearsComponent,
  },
])
export class ApplicationComponent {}

学年组件

import { Component } from '@angular/core';
import { Routes, ROUTER_DIRECTIVES } from '@angular/router';
import { SchoolyearsHomeComponent } from './schoolyears.home.component';
import { CreateSchoolyearComponent } from './create.schoolyear.component';

@Routes([
    {
        path: '',
        component: SchoolyearsHomeComponent,
    },
    {
        path: '/create',
        component: CreateSchoolyearComponent
    }
])
@Component({ template: `<router-outlet></router-outlet>`, directives: [ROUTER_DIRECTIVES]})
export class SchoolyearsComponent {
}

schoolyears.component.html

<h3>Schoolyears</h3>

<div>
<a [routerLink]="['/create']">Create</a>
</div>

<table>
    <tr *ngFor="let s of schoolyears" (click)="createSchoolyear()">
        <td>{{s.id}}</td>
        <td>{{s.name}}</td>
        <td>{{s.startDate}}</td>
        <td>{{s.endDate}}</td>
    </tr>
</table>

当我单击“创建”routerLink 时,我收到此错误:

错误

EXCEPTION: Error: Uncaught (in promise): Cannot match any routes. Current segment: 'create'. Available routes: ['/'].

为什么没有加载子路由?为什么 /create 路由不在可用的路由数组中?

4

4 回答 4

7

更新

这在新的 V3-beta.2 路由器中不再相关。

原来的

改变

@Routes([
  {path: '', component: SchoolyearsHomeComponent},
  {path: '/create', component: CreateSchoolyearComponent}
])

@Routes([
  {path: '/create', component: CreateSchoolyearComponent},
  {path: '', component: SchoolyearsHomeComponent},
])

路线的顺序目前很重要。最具体的路线应该放在第一位,最不具体的路线最后。这是一个已知问题,应尽快修复。

于 2016-06-02T05:13:22.797 回答
3

您必须删除前导的“/”,新路由器会为您处理它。

@Routes([
  {path: 'create', component: CreateSchoolyearComponent},
  {path: '', component: SchoolyearsHomeComponent},
])
于 2016-06-24T15:20:59.740 回答
0

您需要将路由器注入到应用程序组件中,如下所示:

 export class AppComponent {

  constructor(private router: Router) {}

}

当与此组件关联的模板不使用该<router-link>指令时,通常需要这样做。最近对 Angular 的更改在仅使用<router-outlet>

于 2016-06-01T22:46:20.967 回答
0

看起来我们在@Routes 中提到的路线顺序是值得注意的。最具体的路线应该放在第一位,最不具体的路线最后。根据它改变你的@Routes到这个

@Routes([
  {path: '/create', component: CreateSchoolyearComponent},
  {path: ' ', component: SchoolyearsHomeComponent},
])`
于 2016-06-27T22:15:57.373 回答