깜놀하는 해므찌로

Angular HTTP 통신 예시 본문

IT

Angular HTTP 통신 예시

agnusdei1207 2023. 4. 8. 10:43
반응형
SMALL
import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormControl } from '@angular/forms';
import { HttpClient } from '@angular/common/http';

// RxJS
import { Subscription, Observable, of, throwError } from 'rxjs';
import { debounceTime, switchMap, map, tap, catchError } from 'rxjs/operators';

interface GithubUser {
  login: number;
  name: string;
}

export class ObservableEventHttpComponent implements OnInit, OnDestroy {

  searchInput: FormControl = new FormControl(''); // input 태그
  githubUser: GithubUser; // user 타입
  subscription: Subscription;

  // HTTP 서버와의 통신을 위해 HttpClient를 의존성 주입
  constructor(private http: HttpClient) {}

  ngOnInit() {
    // 폼 컨트롤 값의 상태를 옵저버블 스트림으로 수신한다.
    this.subscription = this.searchInput.valueChanges // valueChanges 프로퍼티에 의해 옵저버블로 변환
      .pipe(
        // 옵저버블이 방출하는 데이터를 수신하는 시간을 지연시킨다.
        debounceTime(500),
        // 새로운 옵저버블을 생성 및 최신 데이터로 교체
        switchMap((userId: string) => this.getGithubUser(userId))
      )
      // 구독
      .subscribe(
        user => this.githubUser = user,
        error => console.log(error)
      );
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

  // 서버로부터 데이터를 응답받아 옵저버블을 반환한다.
  getGithubUser(userId: string): Observable<GithubUser> {
    return this.http
      .get<GithubUser>(`https://api.github.com/users/${userId}`) // get 통신 결과과
      .pipe( // 스트림 데이터 핸들링링
        map(user => ({ login: user.login, name: user.name })),
        tap(console.log),

        catchError(err => {
          if (err.status === 404) {
            return of(`[ERROR] Not found user: ${userId}`);
          } else {
            return throwError(err);
          }
        })
      );
  }
}
반응형
LIST

'IT' 카테고리의 다른 글

Angular 마우스 좌표  (0) 2023.04.09
앵귤러 angular Router.navigateByUrl / navigate  (0) 2023.04.08
Angular Observable Operator  (0) 2023.04.08
Angular Observable subscirbe  (0) 2023.04.08
typescript array delete by index 요소 1개 삭제 예시  (0) 2023.04.08