iT邦幫忙

2026 iThome 鐵人賽

DAY 8
0
自我挑戰組

Angular 開發二三事系列 第 8 篇

Day8: 寫個 404 頁面

  • 分享至 

  • xImage
  •  

Angular 寫 404 頁面很簡單,跟 Vue 類似。
在 Route 的 path 填上兩個 * 字號就行了!

直接看程式碼:

app.routes.ts

import { Routes } from '@angular/router';
import { authGuard, publicGuard } from '@app/core/guards/global.guard';
import { NotFound } from './pages/not-found/not-found.ts';

export const routes: Routes = [
  {
    path: 'login',
    canActivate: [publicGuard],
    loadComponent: () => import('./pages/login/login.component').then(m => m.LoginComponent),
  },
  {
    path: '',
    canActivate: [authGuard],
    loadComponent: () => import('./pages/home/home.component').then(m => m.HomeComponent),
  },
  {
    path: '**',
    component: NotFound,
  },
];

not-found.ts

import { Component, inject } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-not-found',
  standalone: true,
  template: `
    <div class="not-found-container">
      <h1>404</h1>
      <p>找不到您要存取的頁面</p>
      <button (click)="goHome()">返回首頁</button>
    </div>
  `,
  styles: [`
    .not-found-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100vh;
      text-align: center;
    }
  `]
})
export class NotFound {
  private readonly router = inject(Router);

  protected goHome(): void {
    this.router.navigate(['/']);
  }
}

參考資料


上一篇
Day 7: Angular 的路由守衛 Route Guards
下一篇
Day9: 全域 Loading
系列文
Angular 開發二三事 共 10 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言