Check internet connection in web using Angular 4

后端 未结 10 2123
感情败类
感情败类 2020-12-15 19:37

I am using Angular 4 for my application development. I need to check If the network connection is available for its have any Connection issue using Angular for. Is it possib

10条回答
  •  心在旅途
    2020-12-15 19:47

    We don't need any libraries for this however public onlineOffline: boolean = navigator.onLine; will do the trick but this is just a one time check. We need to treat this value as an observable so whenever the online status change we are updated. For this rxjs will help.

    Import these

    import { Observable, Observer, fromEvent, merge } from 'rxjs';
    import { map } from 'rxjs/operators';
    

    Add this method

      createOnline$() {
        return merge(
          fromEvent(window, 'offline').pipe(map(() => false)),
          fromEvent(window, 'online').pipe(map(() => true)),
          new Observable((sub: Observer) => {
            sub.next(navigator.onLine);
            sub.complete();
          }));
      }
    

    Subscribe to this event from your constructur or ngOnInit

    this.createOnline$().subscribe(isOnline => console.log(isOnline));
    

    Note: Im using Angular 8.1 and rxjs 6.5.2

提交回复
热议问题