깜놀하는 해므찌로

Observable Http통신 배열로 받는 법 예시 / async, await, error 본문

IT

Observable Http통신 배열로 받는 법 예시 / async, await, error

agnusdei1207 2023. 7. 17. 23:22
반응형
SMALL
items$: Observable<any[]> | undefined;

this.items$ = this.httpService.get<any>(
      `서버 요청 url`
    );

1. httpClient 통신 return 값은 Obervable 타입입니다. 따라서 바로 옵저버블타입으로 데이터를 받을 수 있습니다.

2. 받는 옵저버블의 Generic 이 배열이라면 배열로 받아집니다.

 

 // httpService 내부

constructor(private readonly httpClient: HttpClient) {}

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

3. httpService 내부입니다.

 

items: DTO[] = [];

getItems(): void {
    const option: DTO = {
      categoryId: process.env['NX_VIDEO_ID']!,
    };

    this.httpService // 환경 변수
      .get<any>(`서버/주소/${process.env['NX_PROJECT_ID']}`, {
        params: { ...option }, // prisma 사용으로 인한 조건문 옵션 
      })
      .subscribe({
        next: async (data) => { // 통신이므로 async / await 처리
          this.videos = await data;
        },
        error: (error) => { // 통신은 반드시 error 처리
          console.error(error);
        },
      });
  }

4. 일반 사용자 정의 DTO 타입의 배열로도 받을 수 있습니다. 

5. async / await 활용 

 

  async getItems() {
    const option: DTO = {
      categoryId: process.env['NX_VIDEO_ID']!,
    };

    this.videos = await lastValueFrom( // lastValueForm : 구독이 취소됐을 시 마지막 값 반환 및 타입 변환(옵저버블->일반타입)
      this.httpService.get<DTO[]>(
        `post/realated/${process.env['NX_PROJECT_ID']}`,
        {
          params: { ...option },
        }
      )
    );
  }

6. 위 예시의 다른 버전으로 getItems 함수 자체를 async 로 선언합니다.

7. lastValueForm 을 사용하여 값을 할당합니다.

 

반응형
LIST