【问题标题】:Need to add a Independent 404 page in Angular without Header or Footer需要在没有页眉或页脚的Angular中添加独立的404页面
【发布时间】:2020-02-21 10:38:29
【问题描述】:

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

索引.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>

not-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> 

app-routing.module.ts

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

【问题讨论】:

  • 什么是 webLoading ?
  • @A.khalifa 这只是在我们得到 API 响应之前显示的微调器

标签: angular angular8 angular-routing angular-router


【解决方案1】:

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

.hasDisplay {
  display: none;
}

hasDisplay 类必须在你的 Header 和 Footer 的 div 中

并添加

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

希望有用

【讨论】:

    【解决方案2】:

    在您的 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
    }
    

    【讨论】:

    • 我按照这里的步骤进行操作。每当页面是 404PageRoute 时,它似乎都可以工作,其他路由就像它是随机路由一样,例如asds,它会重定向到 404PageRoute,但会显示页眉和页脚。抱歉,如果我没有从您的回答中捕捉到任何内容。
    • 你可以把 this.url = e.url 改成 -> this.url = e.urlAfterRedirects
    猜你喜欢
    • 1970-01-01
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多