Angular 如果出现错误404,是否可以使用ngIf重用组件?如何捕捉错误?

Angular 如果出现错误404,是否可以使用ngIf重用组件?如何捕捉错误?,angular,components,http-status-code-404,angular-ng-if,code-reuse,Angular,Components,Http Status Code 404,Angular Ng If,Code Reuse,我在app-routin.module.ts中有一个根组件,声明为HomeComponent,如果路由未知,我会重用它 const routes : Routes = [ { path: '', component: PrimaryComponent, data: { breadcrumb: 'PRIMARY'}, children: [ { path: '', component: HomeComponent, canActivate: [Hom

我在app-routin.module.ts中有一个根组件,声明为HomeComponent,如果路由未知,我会重用它

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

这通过在面包屑已更改的情况下加载相同的组件来实现其功能。
我的疑问来了。在my HomeComponent的html中,我有一个在主页上显示欢迎消息的跨距,我希望重用所有的布局和设计,通过一条错误消息修改欢迎消息,并重定向到主页

我知道可以使用第二个span和显示我前面提到的错误消息的ngIf。但是,如何捕获错误以生成ngIf的条件?还是有一些直接的角度测量方法?
非常感谢您

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

message = ''; 
constructor(private route:ActivatedRoute, private router:Router) {
  this.message = route.snapshot.data['breadcrumb'] === "Status Error" ? "error message" : "welcome to home page";
}
并在模板中使用该消息变量

<div>{{message}}</div>
{{message}

在路线中添加一些数据以识别错误:

{ path: '**',
  component: HomeComponent,
  data: {
    breadcrumb: 'Status Error',
    error: 404
  }
}
在您的家庭中:

errorView: number;

constructor(private activatedroute: ActivatedRoute){}

ngOnInit() {
      const data = this.activatedroute.snapshot.data;
      if(data.hasOwnProperty('error')) {
        this.errorView = data.error;
      }
}
在HomeComponent html中:

<div *ngIf="errorView === 404">no url matched</div>
没有匹配的url

我建议使用
角度HttpClient:Interceptors
来确定是否发生了错误,或者更具体地说,是发生了什么类型的错误。然后创建一个集中的
服务
,您可以在其中定义一个变量,该变量的状态可以根据是否发生错误进行更改。然后,基于服务中的此变量,您可以使用
*ngIf()
显示错误消息或欢迎消息。

谢谢。它可以工作,但我想使用*ngIf。无论如何,知道处理代码的其他方法是很好的。谢谢。它工作得很好,谢谢。因此我可以应用*ngIf和[hidden]属性。格雷特非常感谢你。我知道这是最正确的方法,但它只是对别人的旧代码的一个小小的修改,我一直在寻找一个更简单的解决方案,不必去钻研所有我不知道的代码。无论如何,我会研究这个方法,因为我正在开发一个我自己的项目,我认为它会非常有用。非常kind@javascript110899很乐意帮忙。