깜놀하는 해므찌로

Angular Observable HTTP 앵귤러 HTTP 통신 feat.Observable 예시 본문

IT

Angular Observable HTTP 앵귤러 HTTP 통신 feat.Observable 예시

agnusdei1207 2023. 7. 12. 18:16
반응형
SMALL

0. HTTP 통신을 위해 app.config 에 모듈을 로드합니다.

 

 

 

 

npx nx generate service --project 프로젝트명

1. cli 를 활룔해 http 서비스를 생성합니다.

 

2. 통신과 관련된 url 상수값을 선언하기 위해 environment.ts 파일 폴더 및 파일을 생성합니다.

3. 제 경우 여러 곳에 요청을 할 것이므로 각각 요청할 서버 위치가 섞이면 헷갈리 수 있으므로 여러개 있는 것입니다.

4. 이번 예시에서는 하나만 사용합니다.

 

 

5. 백엔드 서버에서는 baseUrl 과 projectId  두 개를 받아 해당 프로젝트의 데이터를 DB에서 조회해 리턴하도록 코드가 이미 짜여진 상태입니다.

 

 

import { Injectable } from '@angular/core';
import {
  HttpClient,
  HttpContext,
  HttpHeaders,
  HttpParams,
} from '@angular/common/http'; // HTTP 통신을 위해 로드
import { environment } from '../../environments/environment'; // 방금 전에 만든 서버 관련 상수값 로드

export type HttpServiceOptions = {
  headers?:
    | HttpHeaders
    | {
        [header: string]: string | string[];
      };
  context?: HttpContext;
  observe?: 'body';
  params?:
    | HttpParams
    | {
        [param: string]:
          | string
          | number
          | boolean
          | ReadonlyArray<string | number | boolean>;
      };
  reportProgress?: boolean;
  responseType?: 'json';
  withCredentials?: boolean;
};

@Injectable({
  providedIn: 'root',
})
export class HttpService {

  private readonly baseUrl = `${environment.baseUrl}`; // 상수 baseUrl 속성에 할당

  constructor(private readonly httpClient: HttpClient) {}

  get<T>(url: string, option?: HttpServiceOptions) { // 조회용
    return this.httpClient.get<T>(`${this.baseUrl}/${url}`, {
      ...option,
    });
  }

  post<T>(url: string, body: any, option?: HttpServiceOptions) { // 데이터 전송
    return this.httpClient.post<T>(`${this.baseUrl}/${url}`, body, {
      ...option,
    });
  }

  put<T>(url: string, body: any, option?: HttpServiceOptions) { // 데이터 전송
    return this.httpClient.put<T>(`${this.baseUrl}/${url}`, body, {
      ...option,
    });
  }

  patch<T>(url: string, body: any, option?: HttpServiceOptions) { // 수정
    return this.httpClient.patch<T>(`${this.baseUrl}/${url}`, body, {
      ...option,
    });
  }

  delete<T>(url: string, option?: HttpServiceOptions) { // 삭제
    return this.httpClient.delete<T>(`${this.baseUrl}/${url}`, {
      ...option,
    });
  }
}

 

6. 서비스 부분입니다. 자세한 설명은 주석을 참조해주세요. 

7. 이번 예시에서는 데이터를 조회하는 부분만 보도록 하겠습니다.

 

 

 

 

import { HttpService } from '../../services/http.service';
import { environment } from 'apps/client/src/environments/environment';

constructor(
    private scrollService: ScrollService,
    private router: Router,
    private httpService: HttpService // 좀 전에 생성한 서비스 의존성 주입
  ) {}
  
  
  ngOnInit() { // 페이지 첫 로드 시 데이터를 조회하도록 onInit 후크에서 호출
    this.getItems();
  }
  
  
  getItems() { // 데이터 조회 메소드 선언
  
    this.httpService
      .get<any>(`${environment.projectId}`)
      .subscribe({ // httpService.get : 메소드는 observable 타입을 리턴하므로 곧바로 subscribe 구독
        next: (res) => { // res: 임의로 정한 변수명으로 이 인스턴스에는 서버로부터 받은 응답데이터가 담겨있습니다.
          console.log(res); // 출력으로 알맞게 데이터가 도착했는지 확인
        },
      });
  }

8. 데이터를 조회할 아무 컴포넌트에 좀 전에 생성한 서비스를 주입하고 활용하는 예시입니다.

 

반응형
LIST