【问题标题】:Equivalent of Angular 1 otherwise route in Angular 2Angular 1 的等价物,否则 Angular 2 中的路线
【发布时间】:2016-03-26 16:29:02
【问题描述】:

我正在为我的应用程序使用 Angular 2 路由,它运行良好,但我不知道如何定义“否则”路由。因此,如果当前 URL 不对应于任何“支持的”路由,则将显示一个路由。

这是我当前配置的示例:

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

【问题讨论】:

  • 该功能尚未实现,请查看#2965#4055
  • 这不是你有'useAsDefault'的原因吗?

标签: javascript angularjs typescript angular


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    在 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”网址,您可以执行以下操作:

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

    【讨论】:

    • 重定向不起作用,如果您要重定向到子路由。我建议只使用NotFound 组件并注入Router,这样您就可以在构造函数中重定向。
    【解决方案3】:

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

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

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

    【讨论】:

      【解决方案4】:

      这对我有用:

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

      【讨论】:

        【解决方案5】:

        试试这个

        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

        【讨论】:

          猜你喜欢
          • 2016-04-19
          • 2017-01-19
          • 2017-02-20
          • 1970-01-01
          • 2016-10-17
          • 2016-11-02
          • 1970-01-01
          • 2013-09-16
          相关资源
          最近更新 更多