Angular 6:如果"Cannot match any routes"移动到其他组件

Angular 6: If "Cannot match any routes" moved to other component

我的路由配置如下:

const routes: Routes = [
  { path: '', redirectTo: '/login', pathMatch: 'full' },
  { path: 'login', component: LoginComponent },
  { path: 'dashboard', component: DashboardComponent }
];

现在,如果有人想像 http://localhost:4200/xyz 一样访问 xyz url 那么我会收到此错误

Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'xyz'

但是我想在上面的例子中重定向到登录页面。

知道如何实现吗?

只需添加一个catch-all路径

const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'dashboard', component: DashboardComponent },
  { path: '**', redirectTo: '/login' }
];

您应该添加通配符路由 ** 以捕获任何 unexpected/unmatched/unlisted url 并将重定向添加到 /login.

const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'dashboard', component: DashboardComponent },
  { path: '', redirectTo: '/login', pathMatch: 'full' },
  { path: '**', redirectTo: '/login' }
];

注意 :最后一个路由中的 ** 路径是一个通配符。如果请求的 URL 与配置中先前定义的路由的任何路径不匹配,路由器将 select 此路由。 确保它是路线列表中的最后一个条目!