在Angular 2中,与Angular 1中的路由等效的是什么?

16

我正在使用 Angular 2 的路由功能来开发我的应用程序,它运行得很好,但我不知道如何定义“otherwise”路由。也就是说,如果当前URL与任何“支持”的路由都不对应,则显示一个路由。

以下是我的当前配置示例:

@RouteConfig([
    { path: '/', name: 'Home', component: StoryComponent, useAsDefault: true },
    { path: '/story', name: 'Story', component: StoryComponent },
    { path: '/subscription', name: 'Subscription', component: SubscriptionComponent}
])

3
该功能尚未实现,请查看#2965和#4055。 - Eric Martinez
难道这不是你为什么要使用'useAsDefault'的原因吗? - jornare
5个回答

10

目前在Angular 2中尚未实现此功能。目前最好的解决方案是使用像@Gary展示的解决方案。

{ path: '**', component: PageNotFoundComponent }

Angular路由指南所示。


8
在angular 2中还没有“否则”路由。但是可以使用通配符参数来实现相同的功能,如下所示:
@RouteConfig([
    { path: '/', redirectTo: ['Home'] },
    { path: '/home', name: 'Home', component: HomeComponent },
    // all other routes and finally at the last add
    {path: '/*path', component: NotFound}

这将只加载“NotFound”组件,并且URL与您导航到的相同。如果您希望所有不匹配的路由重定向到“404” URL,可以执行以下操作:

//at the end of the route definitions
{ path: '/404', name: '404', component: PageNotFoundComponent },
{ path: '/*path', redirectTo:['404'] }`

重定向无法正常工作,如果您正在将其重定向到子路由。我建议只是使用 NotFound 组件并注入 Router,这样您就可以在构造函数中进行重定向。 - gerric

3

3
这对我有效:

const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
    // all other routes
  { path: '**', redirectTo: '/home' }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

0

试试这个

RouterModule.forRoot([
    { path: 'login', component: LoginComponent },
    { path: 'edit-event', component: EventComponent },
    { path: 'participants', component: ParticipantsComponent },
    { path: 'notification', component: NotificationComponent },
    { path: '', component: WelcomeComponent }, //default
    { path: '**', component: WelcomeComponent } //page not found route
], { useHash: true })

useHash参数用于使用哈希URL样式 https://angular.io/docs/ts/latest/guide/router.html#!#route-config


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接