gpt4 book ai didi

Angular2路由器(@angular/router),如何设置默认路由?

转载 作者:太空狗 更新时间:2023-10-29 16:46:08 26 4
gpt4 key购买 nike

如何在我的@Routes 路由元数据集合中设置默认路由?如果你使用来自 @angular/router-deprecated 的 angular2 路由器,你可以在 @routeConfig 对象中定义路由,它是路由对象的集合,但这些路由对象有更多的属性。例如,它们具有 'name' 和 'useAsDefualt' 属性,而在 @angular/router 之外定义的路由则没有。我想使用新路由器编写我的新应用程序,但如何使用新路由器并设置默认路由?

这是我的主要应用程序组件,它定义了我的路线:

import { Component } from '@angular/core';
import { DashboardComponent } from './dashboard/dashboard.component';
import { ConfigManagerComponent } from './configManager/configManager.component';
import { ApplicationMgmtComponent } from './applicationMgmt/applicationMgmt.component';
import { MergeComponent } from './merge/merge.component';

import { ROUTER_DIRECTIVES, Routes } from '@angular/router';


@Component({
selector: 'app-container',
templateUrl: 'app/app.component.html',
directives: [ROUTER_DIRECTIVES]
})

@Routes([

{ path: '/Dashboard', component: DashboardComponent },
{ path: '/ConfigManager', component: ConfigManagerComponent },
{ path: '/Merge', component: MergeComponent },
{ path: '/ApplicationManagement', component: ApplicationMgmtComponent }
])

export class AppComponent { }

当我点击像这样的 anchor 标记时,路由定义似乎工作正常:

<li class="nav hidden-xs"><a [routerLink]="['./Dashboard']">Dashboard</a>/li>

它转换到关联的路线。我唯一的问题是,当我的应用程序加载时,它没有激活的路由。我如何定义在我的应用程序启动时处于事件状态的默认路由?

谢谢!

最佳答案

V2.0.0 及更高版本

另见 https://angular.io/guide/router#the-default-route-to-heroes

RouterConfig = [
{ path: '', redirectTo: '/heroes', pathMatch: 'full' },
{ path: 'heroes', component: HeroComponent,
children: [
{ path: '', redirectTo: '/detail', pathMatch: 'full' },
{ path: 'detail', component: HeroDetailComponent }
]
}
];

还有一条catch-all路线

{ path: '**', redirectTo: '/heroes', pathMatch: 'full' },

重定向“无效”网址。

V3-alpha(符拉迪沃斯托克)

使用路径 /redirectTo

RouterConfig = [
{ path: '/', redirectTo: 'heroes', terminal: true },
{ path: 'heroes', component: HeroComponent,
children: [
{ path: '/', redirectTo: 'detail', terminal: true },
{ path: 'detail', component: HeroDetailComponent }
]
}
];

RC.1 @angular/router

RC 路由器还不支持useAsDefault。作为解决方法,您可以明确导航。

在根组件中

export class AppComponent {
constructor(router:Router) {
router.navigate(['/Merge']);
}
}

对于其他组件

export class OtherComponent {
constructor(private router:Router) {}

routerOnActivate(curr: RouteSegment, prev?: RouteSegment, currTree?: RouteTree, prevTree?: RouteTree) : void {
this.router.navigate(['SomeRoute'], curr);
}
}

关于Angular2路由器(@angular/router),如何设置默认路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37605119/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com