Environment Configuration: environment.ts สำหรับ dev/prod

Environment Configuration คือการแยกค่าตั้งค่าตามสภาพแวดล้อม เช่น development และ production เพื่อให้ Angular ใช้ API URL หรือ feature flag ที่ต่างกันโดยไม่ต้องแก้ code หลักทุกครั้ง

Timeline/ประวัติศาสตร์

%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#fabd2f", "primaryTextColor": "#282828", "primaryBorderColor": "#b57614", "lineColor": "#7c6f64", "secondaryColor": "#83a598", "tertiaryColor": "#b8bb26", "background": "#fbf1c7", "mainBkg": "#ebdbb2", "fontFamily": "Tahoma, sans-serif"}}}%%
flowchart LR
  subgraph Era1["ยุค Hardcode / Fixed Config"]
    A["apiUrl ใน code
แก้ยากและพลาดง่าย"] end subgraph Era2["ยุค Build Config / Angular Environments"] B["environment.ts
dev config"] C["environment.prod.ts
production config"] end subgraph Era3["ยุค Runtime Config / Hosting"] D["Server Environment
secret บน hosting"] E["CI/CD Variables
config ตอน deploy"] end A --> B --> C --> D --> E

แนวคิดสำคัญ

ตาราง dev/prod config

ค่า Development Production
production false true
apiUrl http://localhost:3000 https://api.example.com
Logging เปิดได้มาก จำกัด
Secret ห้ามฝังใน frontend อยู่ฝั่ง server

Mermaid Diagram: File Replacement

%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#fabd2f", "primaryTextColor": "#282828", "primaryBorderColor": "#b57614", "lineColor": "#7c6f64", "secondaryColor": "#83a598", "tertiaryColor": "#b8bb26", "background": "#fbf1c7", "mainBkg": "#ebdbb2", "fontFamily": "Tahoma, sans-serif"}}}%%
flowchart TD
  A["ng build
คำสั่ง build"] --> B{"configuration?
dev หรือ production"} B -->|development| C["environment.ts
api localhost"] B -->|production| D["environment.prod.ts
api domain จริง"] C --> E["Angular Bundle
ไฟล์ที่ deploy"] D --> E

Code Example

// src/environments/environment.ts
// ค่า config สำหรับ development
export const environment = {
  production: false,
  apiUrl: 'http://localhost:3000'
};
// src/environments/environment.prod.ts
// ค่า config สำหรับ production
export const environment = {
  production: true,
  apiUrl: 'https://api.example.com'
};
// lesson-api.service.ts
// อ่าน apiUrl จาก environment แทนการ hardcode
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from '../environments/environment';

@Injectable({ providedIn: 'root' })
export class LessonApiService {
  private apiUrl = environment.apiUrl;

  constructor(private http: HttpClient) {}

  getLessons() {
    return this.http.get(`${this.apiUrl}/api/lessons`);
  }
}

// ตัวอย่างการใช้งาน:
// ng build --configuration production จะใช้ environment.prod.ts ตาม fileReplacements

วิดีโอแนะนำ

กิจกรรมท้ายบท

  1. สร้าง apiUrl ใน environment dev/prod
  2. แก้ service ให้อ่านค่าจาก environment
  3. ทดลอง build แบบ production
  4. อธิบายว่าทำไม secret ไม่ควรอยู่ใน frontend bundle

กลับสัปดาห์ที่ 13