以编程方式处理丢失/错误的路由

时间:2016-04-02 22:06:11

标签: routing angular

假设我们有三条路线:

  • /
  • /登录
  • /报告

如果用户手动输入不存在的路线,目前会向控制台抛出错误,例如/ bla-bla:

browser_adapter.js?d744:76 Error: Uncaught (in promise): ObjectUnsubscribedError
at resolvePromise (angular2-polyfills.js:543)
at angular2-polyfills.js:579
at ZoneDelegate.invokeTask (angular2-polyfills.js:365)
at Object.NgZoneImpl.inner.inner.fork.onInvokeTask (ng_zone_impl.js?ae31:35)
at ZoneDelegate.invokeTask (angular2-polyfills.js:364)
at Zone.runTask (angular2-polyfills.js:263)
at drainMicroTaskQueue (angular2-polyfills.js:482)
at ZoneTask.invoke (angular2-polyfills.js:434)

网址仍然无效:/ bla-bla。

我想知道是否可以安装路由错误处理程序以便能够响应?

1 个答案:

答案 0 :(得分:2)

您可以添加路径为/**的定义:

@RouteConfig([
  {path:'/',name:'Home',component:HomeComponent},
  {path:'/reports',name:'Reports',component:ReportsComponent},
  {path:'/login',name:'Login',component:LoginComponent},
  {path:'/**',component:InvalidRouteComponent}
])

路径:/**将匹配尚未定义的每条路径。

在InvalidRouteComponent中,您可以注入Router来访问lastNavigationAttempt:

@Component({
    selector: 'default-route',
    template: 'This is an invalid path: {{lastRoute}}'
})
export class DefaultComponent {
  lastRoute:string;
  constructor(private _router:Router){
    this.lastRoute = _router.root.lastNavigationAttempt;
  }
}