angular - 重定向 Angular 2 中的不匹配路由

标签 angular angular2-routing

<分区>

我正在寻找 $urlRouterProvider.otherwise 的等价物在 Angular 2 中。

更多详情:

我有一个这样的路由器定义:

@RouteConfig([
  { path: "/", component: MultiPost, name: "Home", useAsDefault: true },
  { path: "/m/:collectionName/:categoryName/:page", component: MultiPost, name: "MultiPost" }
])

两条路线都运行良好,例如当我点击 / 时或 /m/sth/sth/0我得到了我想要的。

但是当我点击一个随机的 url,比如 /kdfsgdshdjf什么都没发生。页面呈现并且<router-outlet>为空,因为没有路由匹配。

我想做的是将所有不匹配的路由重定向到默认路由。我需要类似 $urlRouterProvider.otherwise("/"); 的东西.

有人知道怎么做吗?

最佳答案

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'] }

关于angular - 重定向 Angular 2 中的不匹配路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34906802/

相关文章:

html - 如何将选定复选框的值作为数组发送到函数?

html - 从 html 模板 [angular] 中的 typescript 文件调用变量

Angular:解析失败时显示目标 URL

angular - 如何以 Angular 2获取当前路线自定义数据?

带参数的 Angular2 辅助路由

angular - 错误: Failed to load the template in ES5 Angular2

javascript - 在 Angular2 中动态绑定(bind)模型

在路由中使用 loadchildren 时,Angular 5 子路由在根级路由器导出加载

angular - 设置路线时在 Angular 2中使用名称

javascript - Angular 2 编译失败