Advertisement
Guest User

Untitled

a guest
Jan 17th, 2020
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const PING_INTERVAL = 1000;
  2. const PING_URL = 'http://localhost:4200';
  3. const online$ = new BehaviorSubject<boolean>(navigator.onLine);
  4. const ping$ = online$.pipe(
  5.   mergeMap((online) => {
  6.     if (online) {
  7.       return interval(PING_INTERVAL).pipe(
  8.         takeWhile(() => !!online$.value),
  9.         mergeMap(() => {
  10.           return fromPromise(fetch(PING_URL, {
  11.             method: 'head',
  12.             mode: 'cors',
  13.           }).then());
  14.         }),
  15.         pluck('status'),
  16.         map(status => status === 200),
  17.       );
  18.     }
  19.     return of(online);
  20.   }),
  21. );
  22.  
  23. window.addEventListener('online', () => {
  24.   online$.next(navigator.onLine);
  25. });
  26.  
  27. window.addEventListener('offline', () => {
  28.   online$.next(navigator.onLine);
  29. });
  30.  
  31.  
  32. online$.subscribe((yeah) => console.log('online is', yeah));
  33.  
  34. ping$.subscribe((status) => console.log('ping', status));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement