ionic app 监听网络功能

安装cordova插件:

cordova plugin add cordova-plugin-network-information

 

在app.js 的run()里面的function()注入$cordovaNetwork,然后就可以监听网络的链接状态和断开状态了,部分代码如下:

    .run(function($ionicPlatform,$state,$ionicPopup,$ionicLoading,$rootScope,$ionicHistory,$ionicViewSwitcher,$cordovaNetwork) {
        $ionicPlatform.ready(function() {
            // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
            // for form inputs)
            if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
                cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
                // cordova.plugins.Keyboard.disableScroll(false);
            }
            if (window.StatusBar) {
                StatusBar.styleDefault();
            }  

            //监听网络
            $rootScope.$on('$cordovaNetwork:online', function (event, networkState) { 
                var onlineState = networkState;
                $ionicLoading.show({
                    template: '网络已恢复',
                    noBackdrop :true,
                    duration: 2500
                }); 
            })  
            $rootScope.$on('$cordovaNetwork:offline', function (event, networkState) { 
                var offlineState = networkState; 
                $ionicLoading.show({
                    template: '网络异常,不能连接到服务器!',
                    noBackdrop :true,
                    duration: 2500
                });  
            }) 

        });

 

另外,顺带附上一个ionic ngCordova 的参考文档,非常有用,在此记录一下:http://www.ionic-china.com/doc/ngCordova/

 

posted @ 2017-04-28 14:08  FEer_llx  阅读(409)  评论(0编辑  收藏  举报