需要在 Angular 中添加一个没有页眉或页脚的独立 404 页面

Need to add a Independent 404 page in Angular without Header or Footer

我已经创建了一个 Angular 应用程序,为此,如果用户指向一个未知的 URL,它应该进入一个 404 页面,显示一条友好的消息以重定向到主页。 现在我创建了一个显示此 404 的组件。现在的问题是,它显示了页眉和页脚。在这种情况下,我不希望显示页眉和页脚 The page right now 我需要显示没有页眉和页脚的 404。有没有什么简单的方法可以实现。提前致谢。

Index.html

<body>
  <app-root></app-root>
</body> 

app.component.html

<div *ngIf="!webLoading">
    <app-header></app-header>
    <div class="minhgt-router-outlet">
        <router-outlet></router-outlet>
    </div>
    <app-footer></app-footer>
</div>
<div class='modal d-flex carousel' *ngIf="webLoading">
    <p-progressSpinner [style]="{width: '50px', height: '50px'}" 
    strokeWidth="4" fill="#ffffff" animationDuration=".8s"></p-progressSpinner>
</div>

不是-found.component.html

<div class="notfound">
        <div class="notfound-404">
            <h3>Oops! Page not found</h3>
            <h1>
                <span>4</span>
                <span>0</span>
                <span>4</span>
            </h1>
        </div>
        <h2>we are sorry, but the page you requested was not found</h2>
</div> 

应用-routing.module.ts

const routes: Routes = [
  {
    path: "",
    component: BodyContentComponent
  },
{ 
    path: "**", 
    component: NotFoundComponent
   }
];

在你的css的not-found.component中添加

.hasDisplay {
  display: none;
}

hasDisplay class 必须在您的 div 页眉和页脚

并添加

 @Component({
  selector: 'app-not-found',
  templateUrl: './not-found.component.html',
  styleUrls: ['./not-found.component.scss'],
  encapsulation: ViewEncapsulation.None
})

希望有用

在您的 AppComponent 中,您可以订阅路由器事件并检查当前 URL,并根据模板文件中的条件添加条件。

url: string;

ngOnInit(): void {
  this.router.events.pipe(
    filter((event) => event instanceof NavigationEnd),
    map((e: NavigationEnd) => this.url = e.urlAfterRedirects)
  ).subscribe();
}

然后,在您的模板中,

<ng-container *ngIf="url !== '/404url'"> <app-header></app-header></ng-container>

此外,要使其正常工作,您应该有一个特定的 404 页面路由,并将所有通配符路由重定向到该页面。

{
  path: '**',
  redirectTo: '404PageRoute',
  pathMatch: 'full'
},  {
  path: '404PageRoute',
  component: NotFountcomponent
}