개발/front-end

Angular rxjs 비동기 처리 예제

희운1205 2024. 7. 5. 08:35
반응형

rxjs 비동기 처리 예제
* 라우터 이동 혹은 5분에 한 번씩 api를 다시 조회

const REFRESH_INTERVAL = 60000 * 5; // 5분

public data$ = new Observable();
private cache1$: Observable<any> | undefined;

get SyncData(): any {
    if (!this.cache1$) {
      const timer$ = timer(0, REFRESH_INTERVAL);
      const router$ = this.router.events.pipe(filter(e => e instanceof NavigationEnd));
      this.cache1$ = merge(router$, timer$).pipe(
        distinctUntilChanged(),
        switchMap(_ => this.fetch('/api/data.php', 'get')),
        shareReplay(1)
      );
    }
    return this.cache1$;
}

this.data$ = this.SyncData



반응형