0
我已經編寫了以下服務,它試圖檢查應用程序的連接性,就像在我的Ionic應用程序中一樣,我需要根據用戶是脫機還是聯機來執行某些操作。目前我遇到3個問題。檢查Ionic應用程序的網絡狀態
1)在我的桌面上,當在瀏覽器中測試時,即使當我的wifi不工作時,我總是會收到You are not connected
消息。我怎樣才能讓它在我的桌面上顯示正確的消息?
2)在我的手機上,我已經測試過這個,並且它確實能夠正常工作並正確設置連接狀態,但是如果我打開/關閉無線連接,它不會立即刷新並需要一些時間。我怎樣才能讓它在我的移動應用程序上「實時」更新。
connection.service.js
(function() {
'use strict';
angular
.module('dingocv.services')
.service('ConnectionService', ConnectionService)
function ConnectionService($rootScope, $cordovaNetwork) {
this.isOnline = function() {
if(ionic.Platform.isWebView()) {
return $cordovaNetwork.isOnline();
} else {
return navigator.OnLine;
}
}
this.isOffline = function() {
if(ionic.Platform.isWebView()) {
return !$cordovaNetwork.isOnline();
} else {
return !navigator.OnLine;
}
}
this.startWatching = function() {
if(ionic.Platform.isWebView()) {
$rootScope.$on('$cordovaNetwork:online', function(event, networkState) {
console.log('went online');
});
$rootScope.$on('$cordovaNetwork:offline', function(event, networkState) {
console.log('went offline');
});
} else {
window.addEventListener('online', function(e) {
console.log('went online');
}, false);
window.addEventListener('offline', function(e) {
console.log('went offline');
}, false);
}
}
}
})();
search.controller.js
(function() {
'use strict';
angular
.module('dingocv.controllers')
.controller('SearchController', SearchController)
function SearchController($scope, CategoryService, ConnectionService) {
if(ConnectionService.isOnline()){
$scope.connected = true;
} else {
$scope.connected = false;
}
CategoryService.getCategoryList().then(function(dataResponse) {
$scope.categories = dataResponse.data;
});
}
})();
search.view.html
<ion-view view-title="Search">
<ion-content>
<div ng-show="!connected">
You are not connected
</div>
<div ng-show="connected">
You are connected
</div>
</ion-content>
</ion-view>