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

时间:2015-12-20 13:24:31

标签: javascript angularjs typescript angular

我正在为我的应用程序使用Angular 2路由,它运行得很好,但我不知道如何定义"否则"路线。因此,如果当前URL不对应任何"支持的#34;路由。

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

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

5 个答案:

答案 0 :(得分: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}

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

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

答案 1 :(得分:8)

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

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

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

答案 2 :(得分:3)

尝试这个而不是其他。它对我有用,不确定,但似乎正在进行中。

@RouteConfig([
  { path: '/**', redirectTo: ['MycmpnameCmp'] }, 
   ...
  }
])

https://github.com/angular/angular/issues/4055

答案 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 { }

答案 4 :(得分: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