Skip to content

Service & HttpClient#

Service#

  • Angular核心元件
  • 專門處理某事情
    • component → 畫面、資料綁定
    • service → 取得資料、邏輯處理
  • 模組化、增加重用性
  • component 使用 Dependency Injection (依存注入) Service
  • 通常 component 會共用一個 Service
  • Service 的裝飾詞
    • @Injectable

Service 註冊在#

  1. @Injectable 等級

    • 在 service
    • 'root' 範圍在整個 app
    @Injectable({
        providedIn: 'root'
    })
    
  2. @ngModule 等級

    • 在 app.module
    • 範圍在當前 module
    @NgModule({
        providers: [Service1]
    })
    
  3. @component 等級

    • 在 .component.ts
    • 範圍在當前 component
    @Component({
        providers: [Service2]
    })
    

HttpClient#

  • 以 Http 協定與後端服務進行通訊
  • 引用 @angular/common/http 的 HttpClientModule
  • 以 DI 方式帶入 HttpClient

Http 方法#

get(url: string, options)

post(url: string, body: any, options)

put(url: string, body: any, options)

delete(url: string, options)
  • url : 目的端網址
  • options : 最常用 observe 與 responseType

    • observe 指定要回傳的內容

      • body | events | response
      let options = { observe : 'body' }
      
    • responseType 指定格式

      let options = { responseType : 'json' }
      
    • headers 指定標頭資訊

      let options = { headers : new HttpHeaders({
          'Content-Type' : 'text/json' })
      }
      
  • body : 要放在 HTTP Body 的資料

  • 回傳 Observable 或是 Observable<T>

Observable#

  • 可觀察物件傳遞 HttpClient 的回傳值
    • 通常用於非同步設計及事件處理
  • 使用 subscribe() 方法並傳入一個 observer
  • observer 物件定義回呼叫函式
    • next: 必要當處理的值送達時值行,可值行0-n次
    • error: 可省略,處理錯誤
    • complete: 可省略,處理執行完畢時的通知
  • See more detail in: RxJS

RESTful Service#

  • REST → Representational State Transfer
  • 在不同架構、網路互相傳遞資訊
  • 使用 HTTP 協定時做資料交換的一致性
  • 基於 HTTP、URI、XML、HTML、JSON
    • 對應HTTP協定的GET、POST、PUT、DELETE
  • 以資源(URI)為基礎

ASP.Net Web API#

  • ASP.NET Core MVC的一部分
  • 是REST-style AP
  • 使用URL提出請求
    • 讓存取程式變得更簡單易寫
    • 回應資料支援JSON格式
  • 資源存取的邏輯重複使用
  • Web API 的控制器由 ControllerBase 類別繼承
  • [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase {}
    
  • 提供的方法

    方法 狀態碼
    OK() 200
    BadRequest() 400
    NotFound() 404
    PhysicalFile() 回傳檔案

回應的型別#

  • IActionResult

    • 回應多種類型
    [HttpGet("{id}")]
    public IActionResult Get(int id) {..............}
    
  • ActionResult

    • Core 2.1 之後引進
    • 透過泛型指定回應型別
    [HttpGet("{id}")]
    public ActionResult<string> Get(int id) {.........}
    

CORS#

  • 預防網頁不同網域提出需求
  • 伺服器端需要啟用