Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 스크롤 이벤트
- 모달
- 스크롤 이벤트 감지
- 옵저버블
- scroll
- Oracle LISTAGG 사용 예시
- Router
- 앵귤러 애니메이션
- angular animation
- mysql if
- 검색
- Ionic modal
- angular route
- summary
- 호버
- modal
- prisma
- TAILWIND
- formgroup
- angular modal
- 셀렉트박스 커스텀
- ApexChart
- route
- 아이오닉 스크롤 이벤트
- Angular Router
- egov spring ajax 사용 예시
- flex-1
- 앵귤러 모달
- angular button
- ajax 사용 예시
Archives
- Today
- Total
깜놀하는 해므찌로
Angular HTTP 통신 예시 본문
반응형
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 |