使用ngIf在错误404的情况下重用组件,可以吗?如何捕获错误?

问题描述 投票:0回答:1

我在声明为HomeComponent的app-routin.module.ts中有一个根组件,在路由未知的情况下可以重用

const routes : Routes = [
{
  path: '',
  component: PrimaryComponent,
  data: { breadcrumb: 'PRIMARY'},
  children: [
    { path: '',
      component: HomeComponent,
      canActivate: [HomeGuard],
      pathMatch: 'full',
      data: {breadcrumb: 'Start'}
    },
    ....
    ....
    ....
    { path: '**',
      component: HomeComponent,
      data: {breadcrumb: 'Status Error'}
    }
   ]
 }
];

这通过将更改的面包屑加载到相同的组件来实现其功能。我的疑惑到了。在我的HomeComponent的html内,我有一个跨度,在主页上显示欢迎消息,并且我想重用所有布局和设计,以通过带有重定向到首页的错误消息的错误消息来修改该欢迎消息。

我知道可以将第二个跨度与ngIf一起使用,它显示了我之前提到的错误消息。但是,如何捕获错误以为ngIf生成条件?还是有一些直接的角度方法?预先非常感谢

angular components http-status-code-404 angular-ng-if code-reuse
1个回答
0
投票

您可以尝试获取路线数据(面包屑值)并基于该值设置消息的值

message = ''; 
constructor(private route:ActivatedRoute, private router:Router) {
  if(route.snapshot.data['breadcrumb'] === "Status Error") {
     this.message = "error message";
  } else {
     this.message = "welcome to home page";
 }
}

并在模板中使用该消息变量

<div>{{message}}</div>
© www.soinside.com 2019 - 2024. All rights reserved.