Angular 개발 시 api 통신을 하기 위한 Fetch API에 대해 알아보겠습니다.
 Fetch API 란
Fetch API는 HTTP 파이프라인을 구성하는 요청과 응답 등의 요소를 JavaScript에서 접근하고 조작할 수 있는 인터페이스를 제공합니다. Fetch API가 제공하는 전역 fetch() 메서드로 네트워크의 리소스를 쉽게 비동기적으로 취득할 수도 있습니다.
 설치
Fetch API를 사용하기 위해 cross-fetch 패키지를 설치한다.
1 2 3 4 5
   |  npm install --save cross-fetch
 
  yarn add cross-fetch
 
  | 
 
 ApiService 구축
api는 전역에서 사용하는 것이기 때문에 service로 만든다.
src/app/services 폴더 아래에 api.service.ts 파일을 만들었다.
1 2 3 4 5 6 7 8 9
   |  import { Injectable } from '@angular/core';
  @Injectable({   providedIn: 'root', }) export class ApiService {   constructor() {} }
 
  | 
 
 http 메서드 설정
HTTP 요청 메소드에서 자주 사용하는 GET, POST, PUT, DELETE 를 사용하는 함수를 생성한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
   | import { Injectable } from '@angular/core'; import fetch from 'cross-fetch';
  @Injectable({   providedIn: 'root', }) export class ApiService {   constructor() {}
    public get(url: string): Promise<Response> {     return this.fetch(url, {       method: 'GET',       headers: {         'Content-type': 'application/json',       },     });   }
    public post(url: string, payload: BodyInit): Promise<Response> {     return this.fetch(url, {       method: 'POST',       body: payload,       headers: {         'Content-type': 'application/json',       },     });   }
    public put(url: string, payload: BodyInit): Promise<Response> {     return this.fetch(url, {       method: 'PUT',       body: payload,       headers: {         'Content-type': 'application/json',       },     });   }
    public delete(url: string): Promise<Response> {     return this.fetch(url, {       method: 'DELETE',       headers: {         'Content-type': 'application/json',       },     });   } }
  | 
 
fetch의 return 타입은 Promise 이기 때문에 then 함수를 사용하거나 async await 를 사용한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
   |  import { Component, OnInit } from '@angular/core'; import { ApiService } from 'app/services/api.service';
  @Component({   selector: 'app-root',   templateUrl: './app.component.html',   styleUrls: ['./app.component.scss'], }) export class AppComponent implements OnInit {   private BASE_URL = 'https://webtoon-crawler.nomadcoders.workers.dev';
    constructor(private api: ApiService) {     this.api.get(`${BASE_URL}/today`).then((response: any) => {       if (response.ok) {         console.log(response.json());       }     });   }
    ngOnInit(): void {} }
 
  | 
 
 참고