Environment Configuration คือการแยกค่าตั้งค่าตามสภาพแวดล้อม เช่น development และ production เพื่อให้ Angular ใช้ API URL หรือ feature flag ที่ต่างกันโดยไม่ต้องแก้ code หลักทุกครั้ง
%%{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
src/environments/environment.ts ใช้เช่น { production: false, apiUrl: 'http://localhost:3000' }environment.prod.ts ใช้เช่น { production: true, apiUrl: 'https://api.example.com' }fileReplacements ใน angular.json ใช้แทนที่ไฟล์ตาม configurationng build --configuration production ใช้ production environment อัตโนมัติ| ค่า | Development | Production |
|---|---|---|
production |
false |
true |
apiUrl |
http://localhost:3000 |
https://api.example.com |
| Logging | เปิดได้มาก | จำกัด |
| Secret | ห้ามฝังใน frontend | อยู่ฝั่ง server |
%%{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
// 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
apiUrl ใน environment dev/prod