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

Redirect non-matching routes in Angular 2

我正在寻找 Angular 中 $urlRouterProvider.otherwise 的等价物 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("/");.

这样的东西

有人知道怎么做吗?

此功能尚未实现:

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

angular2 中还没有 'otherwise' 路线。但是使用通配符参数可以实现相同的功能,如下所示:

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