Angular Tips: Base API URL ด้วย Interceptor

tumit
tumit
Sep 7, 2018 · 1 min read

วันนี้มี Tip เล็กๆที่มาจาก วันก่อนเจอ ยิ้ม ถามว่า HttpClient ของ Angular ไม่มีให้เซ็ท Base API URL เหรอ ? ก็ตอบด้วยความมั่นใจว่า “ไม่รู้” lol … จากนั้นด้วยความข้องใจก็เลยไปลองๆหาดูเลยได้ท่านี้มาแชร์กัน

มาดูตัวอย่างกัน

สมมุติเรามี TodoService ไว้เรียก API เวลาเรา implement หน้าตาก็จะประมาณนี้ (ตัวอย่างนี้ใช้ http://jsonplaceholder.typicode.com/ เป็น Fake Online REST API)

ก็ดูโอเคดี แต่ถ้าเรา UserService ที่ไว้เรียก API ด้วยล่ะ ?

จะเห็นว่าบรรทัดที่ 19: apiUrl จะ duplicate อยู่ ท่ามาตราฐานคือเราย้าย config ไปไว้ที่ environment.ts แล้วเรียกผ่าน environment.apiUrl

// remove hard config => todo.service.ts & user.service.ts
readonly apiUrl = environment.apiUrl;

แต่…

ปัญหาคือ ก็ยังต้องคอยเติม environment.apiUrl ในทุกๆ service ใหม่ๆที่เพิ่มเข้ามา เลยลองไป google เจอว่ามีคนใช้ Interceptor ในการแอบบเซ็ต apiUrl ก่อนจะส่ง request ได้ ก่อนอื่นสร้าง interceptor ไฟล์ขึ้นมาก่อนด้วย

  • บรรทัด 12: เรียก environment.apiUrl มาไว้ใน interceptor
  • บรรทัด 13: ทำการ clone request แล้วแอบเอา apiUrl ไปหยอดก็จะส่ง request ไปจริงๆ

แล้ว config ให้ AppModule เราใช้ BaseUrlInterceptor ที่เราสร้างขึ้นมา

จากนั้นก็ปรับให้ service ส่งแค่ path ที่ต้องการเป็น

// todo.service.ts
return this.http.get<Todo[]>(‘/todos’);
and...// user.service.ts
return this.http.get<User[]>(‘/users’);

จบปิ๊ง

Refs: https://stackoverflow.com/questions/34516651/set-base-url-for-angular-2-http-requests

odds.team

Odds Team

tumit

Written by

tumit

odds.team

odds.team

Odds Team

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade