Week 08 · Day 01 — 服務與 Dependency Injection(依賴注入)

學習目標

  • 理解依賴注入(DI)概念
  • 建立 @Injectable 服務
  • 在元件注入並使用服務

重點

依賴注入是什麼 - 「要用什麼就告訴框架,框架幫你建立並送進來」 - 不用自己 new,Angular 的 DI 系統管理實例 - Angular 用 constructor 參數注入:constructor(private auth: AuthService) {}

建立服務

import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })   // root:整個應用共享一個實例
export class AuthService {
  private isLoggedIn = false;

  login(username: string, password: string): boolean {
    // 登入邏輯
    this.isLoggedIn = true;
    return true;
  }

  logout(): void {
    this.isLoggedIn = false;
  }

  isAuthenticated(): boolean {
    return this.isLoggedIn;
  }
}
- @Injectable({ providedIn: 'root' }):單例、全應用可取用

在元件注入

@Component({ ... })
export class DashboardComponent {
  constructor(private authService: AuthService) {}

  get isLoggedIn(): boolean {
    return this.authService.isAuthenticated();
  }
}
- constructor 參數 private authService: AuthService 即注入

優點 - 元件不負責建立服務,測試時可替換(mock) - 狀態可跨元件共享

實作

  1. 建立 AuthService(含 login/logout/isAuthenticated)
  2. 用 CLI:ng g s auth
  3. 在元件注入並取得 isAuthenticated()

作業

  • 建立帶 @Injectable({ providedIn: 'root' }) 的服務
  • 在元件 constructor 注入服務
  • 說出 providedIn: 'root' 的意義