最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can check offline and online in angular - Stack Overflow

programmeradmin6浏览0评论

I have been getting an error from the service call when browse is in offline mode. How can check off-line mode and want to block my service call when the browser is the offline mode?

I have been getting an error from the service call when browse is in offline mode. How can check off-line mode and want to block my service call when the browser is the offline mode?

Share Improve this question edited May 30, 2015 at 10:58 Visakh B Sujathan 1991 gold badge4 silver badges25 bronze badges asked May 30, 2015 at 7:13 Rejayi CSRejayi CS 1,0611 gold badge10 silver badges23 bronze badges 2
  • this I Know my Question is how can block my service call – Rejayi CS Commented May 30, 2015 at 7:17
  • 1 add an http interceptor, that before each call, do this check. – Chen Kinnrot Commented May 30, 2015 at 7:19
Add a ment  | 

3 Answers 3

Reset to default 4

I suggest you to use Offline.js

they have templates and other stuff to work with . you can check out their documentation and see how it works .

it gets you the current state of the connection by returning the "up" or "down" result , or you can bind and event to it and use it across you'r application .

this is what they say about their library :

Offline.js is a library to automatically alert your users when they've lost internet connectivity, like Gmail.

It captures AJAX requests which were made while the connection was down, and remakes them when it's back up, so your app reacts perfectly.

It has a number of beautiful themes and requires no configuration.

good luck and have fun.

Check for navigator.onLineand based on this value decide whether to send request or not.

if (navigator.onLine) {
    $http.get('url').success(function() {});
}
else {
    // no req
}

Angular way:

Use $q service - A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing. https://docs.angularjs/api/ng/service/$q

The best way that I would know would be to intercept the HTTP handler, if its a 401 / 501/ etc. then to handle it according

angular.module('myApp', ['myApp.services'], 
    function ($httpProvider) {

    var interceptor = ['$rootScope', '$q', function ($rootScope, $q) {

        function success(response) {
            return response;
        }

        function error(response) {
            var status = response.status; // error code

            if ((status >= 400) && (status < 500)) {
                $rootScope.broadcast("AuthError", status);
                return;
            }

            if ( (status >= 500) && (status < 600) ) {
                $rootScope.broadcast("ServerError", status);
                return;
            }

            // otherwise
            return $q.reject(response);

        }

        return function (promise) {
            return promise.then(success, error);
        }

    }];
    $httpProvider.responseInterceptors.push(interceptor);

then in your code that listens for the on of, just add in

$rootScope.$on("ServerError", someServerErrorFunction);

Source: How to detect when online/offline status changes

Online/offline detection cannot be 100% accurately decided because network status can vary for a number of reasons.

Still, if you want an implementation of the same with Angular+NGRX, You can find more details here.

https://hackernoon./using-angular-to-detect-network-connection-status-onlineoffline

import { Component, OnDestroy, OnInit, VERSION } from '@angular/core';

import { fromEvent, merge, of, Subscription } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.ponent.html',
  styleUrls: ['./app.ponent.css']
})
export class AppComponent implements OnInit, OnDestroy {
  networkStatus: boolean = false;
  networkStatus$: Subscription = Subscription.EMPTY;

  constructor() {}

  ngOnInit(): void {
    this.checkNetworkStatus();
  }

  ngOnDestroy(): void {
    thisworkStatus$.unsubscribe();
  }

  checkNetworkStatus() {
    thisworkStatus = navigator.onLine;
    thisworkStatus$ = merge(
      of(null),
      fromEvent(window, 'online'),
      fromEvent(window, 'offline')
    )
      .pipe(map(() => navigator.onLine))
      .subscribe(status => {
        console.log('status', status);
        thisworkStatus = status;
      });
  }
}

You can see the demo here.

or check the code here

Happy coding!!!

发布评论

评论列表(0)

  1. 暂无评论