ApplicationComponent
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 {}
SchoolyearsComponent
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路由不在可用的路由数组中?
答案 0 :(得分:7)
<强>更新强>
这在新的V3-beta.2路由器中不再相关。
<强>原始强>
更改
@Routes([
{path: '', component: SchoolyearsHomeComponent},
{path: '/create', component: CreateSchoolyearComponent}
])
到
@Routes([
{path: '/create', component: CreateSchoolyearComponent},
{path: '', component: SchoolyearsHomeComponent},
])
路线的顺序目前很重要。 最具体的路线应该是第一个,最不具体的路线是最后的。 这是一个已知问题,应尽快解决。
答案 1 :(得分:3)
您必须删除前导&#39; /&#39;,新路由器会为您处理。
@Routes([
{path: 'create', component: CreateSchoolyearComponent},
{path: '', component: SchoolyearsHomeComponent},
])
答案 2 :(得分:0)
您需要将路由器注入应用程序组件,如下所示:
export class AppComponent {
constructor(private router: Router) {}
}
当与此组件关联的模板不使用<router-link>
指令时,通常需要这样做。仅使用<router-outlet>
答案 3 :(得分:0)
看起来我们在@Routes中提到的路线顺序是值得注意的。最具体的路线应该是第一个,最不具体的路线是最后的。根据它将@Routes改为此
@Routes([
{path: '/create', component: CreateSchoolyearComponent},
{path: ' ', component: SchoolyearsHomeComponent},
])`