等效于角度1,否则在Angular 2中路由

sso*_*nez 13 javascript angularjs typescript angular

我正在为我的应用程序使用Angular 2路由,它工作得很好,但我不知道如何定义"其他"路由.因此,如果当前URL与任何"支持"路由不对应,则将显示的路由.

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

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

SaU*_*rYa 8

角度2中没有"其他"路线.但是使用通配符参数可以实现相同的功能,如下所示:

@RouteConfig([
    { path: '/', redirectTo: ['Home'] },
    { path: '/home', name: 'Home', component: HomeComponent },
    // all other routes and finally at the last add
    {path: '/*path', component: NotFound}
Run Code Online (Sandbox Code Playgroud)

这将仅加载'NotFound'组件,并且url将与您导航到的相同.如果您希望所有不匹配的路由重定向到'404'网址,您可以执行以下操作:

//at the end of the route definitions
{ path: '/404', name: '404', component: PageNotFoundComponent },
{ path: '/*path', redirectTo:['404'] }`
Run Code Online (Sandbox Code Playgroud)


ahe*_*ins 8

目前还没有在角度2中实现.目前最好的解决方案是使用像@Gary这样的解决方案.

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

如角度指南路由部分(https://angular.io/docs/ts/latest/guide/router.html)所示.