Week 06 · Day 01 — HttpClient 基礎

學習目標

  • 安裝並啟用 HttpClientModule
  • 建立一個封裝 HTTP 的 Service
  • http.get() 取得資料

重點

啟用 HttpClientModule

// app.module.ts
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [HttpClientModule]
})

使用服務封裝 HTTP(推薦) - 把 API 呼叫放在 Service,元件只呼叫服務 - 用 @Injectable({ providedIn: 'root' }) 讓全應用共用一個實例

// user.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class UserService {
  private apiUrl = 'https://api.example.com/users';

  constructor(private http: HttpClient) {}

  getUsers(): Observable<User[]> {
    return this.http.get<User[]>(this.apiUrl);
  }
}

HttpClient methods | 方法 | HTTP | 用途 | |------|------|------| | get<T> | GET | 取得 | | post<T> | POST | 建立 | | put<T> | PUT | 更新(完整) | | patch<T> | PATCH | 更新(部分) | | delete<T> | DELETE | 刪除 |

實作

  1. import HttpClientModule
  2. 建立 UserService,實作 getUsers()
  3. 在元件注入服務並訂閱結果

作業

  • 啟用 HttpClientModule
  • 建立封裝 API 的 Service
  • http.get<User[]> 取得並印出資料