【发布时间】:2016-09-04 17:47:51
【问题描述】:
过去适用于 beta /... 的方法不再有效。使用新的新 RC1 路由器,如何进行子路由?
文件夹结构
app
|--home/
| |--home.component.ts
|--login/
| |--login.ts
|--appShell/
| |--app.component.ts
|--apps/
|--hero/
|--hero-shell.component.ts
|--horees.component.ts
|--hero-detail.component.ts
计划的导航是
app.component -> home.component -> heroshell.component -> heroes.component
app.component.ts 路由
@Routes([
{ path: '/heroshell', component: HeroShellComponent },
{ path: '/home', component: HomeComponent },
{ path: '/login', component: Login },
])
export class AppComponent implements OnInit {
title = 'Apps';
constructor(public _auth: Authentication,
public router: Router,
private _dialogService: DialogService
) {}
ngOnInit() {
this.router.navigate(['/login']);
}
.......
一旦登录成功,Login 类就会
this.router.navigate(['/home']);
从 HomeComponent.ts 我可以做到
this.router.navigate(['/heroshell']);
到目前为止一切顺利,没问题。 在 hero-shell.component.ts 我有子路由
@Component({
selector: 'my-app1',
templateUrl: 'app/apps/hero/hero-shell.component.html',
styleUrls: ['app/appshell/app.component.css'],
directives: [ROUTER_DIRECTIVES],
providers: [HeroService]
})
@Routes([
{ path: 'heroes', component: HeroesComponent },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'hero/:_id', component: HeroDetailComponent},
])
export class HeroShellComponent { // implements OnInit
title = 'Hero Sample App';
constructor(public _auth: Authentication,
public router: Router
) {}
}
在 hero-shell.component.html 中
<my-app1>
<h1>{{title}}</h1>
<!--<button *ngIf="_auth.loggedIn" (click)="onLogout()">Logout</button>-->
<nav>
<a [routerLink]="['dashboard']">Dashboard</a>
<a [routerLink]="['heroes']">Heroes</a>
</nav>
<router-outlet></router-outlet>
</my-app1>
注意路径只能是'heroes'。如果我更改为 [routerLink] 并将 @Routes 更改为 '/heroes',它将无法正常工作。可以帮忙解释一下原因吗?
所以它现在可以识别子路由了。点击routerLink heros会显示英雄列表。但是当我从 HeroesComponent 中详细介绍它时
this._router.navigate(['hero/'+hero._id]);
它被炸毁了
browser_adapter.ts:78 EXCEPTION: Error: Uncaught (in promise):
Cannot match any routes. Current segment: 'hero'.
Available routes: ['/heroshell', '/home', '/login'].
这很奇怪。如果它不识别子路由,我什至怎么能首先进入 HeroesComponent?现在子路由就消失了。
如果我使用
this._router.navigate(['hero/'+hero._id],this.currSegment);
它会给出不同的错误
browser_adapter.ts:78 EXCEPTION:
Error: Uncaught (in promise): Component 'HeroesComponent' does not have route configuration
这是否意味着所有子组件都必须重复使用@Routes?
【问题讨论】:
-
我的代码中存在同样的问题,但我尝试在不附加
/的情况下使用仍然得到相同的错误Cannot match any routes. Current segment: 'hero'. Available routes: ['/heroshell', '/home', '/login'].任何帮助?