首页 > 解决方案 > url参数错误时如何触发通配符路由?

问题描述

在 Angular 6 中,我使用 observable 来管理基于 URL 参数获取详细记录,如下所示:

ngOnInit() {
  this.hero$ = this.route.paramMap.pipe(
    switchMap((params: ParamMap) => {
      const id = parseInt(params.get('id'), 10);
      if (!id) {
        throw new Error('Hero id invalid.');
      }
      return this.service.getHeroById(id);
    }),
    catchError(err => {
      this.router.navigate(['/pageNotFound'], {skipLocationChange: true});
      return throwError(err);
    }),
  );
}

在 catchError 管道中,我只是导航到一个不存在的 URL,这会导致通配符路由触发并显示我的 PageNotFoundComponent。这似乎真的很令人费解,但我不明白如何让路由器显示该组件。有没有更好的办法?

这是我的设置演示: https ://stackblitz.com/edit/angular-router-not-found?file=src%2Fapp%2Fhero%2Fhero-detail.component.ts

标签: angularangular-routerangular-router-params

解决方案


推荐阅读