我有以下代码在我的cordova应用程序中在线/离线检查。
var networkState = navigator.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown';
states[Connection.ETHERNET] = 'Ethernet';
states[Connection.WIFI] = 'WiFi';
states[Connection.CELL_2G] = 'Cell2G';
states[Connection.CELL_3G] = 'Cell3G';
states[Connection.CELL_4G] = 'Cell4G';
states[Connection.CELL] = 'Cellgeneric';
states[Connection.NONE] = 'Nonetwork';
alert(states[networkState]);
if(states[networkState]!='Nonetwork'){
online=true;
}else{
online=false;
}
我的角度控制器如下所示。
.controller('MainCtrl',['$scope','$http','$localStorage','$state',function($scope, $http, $localStorage, $state){
if(online==true){
//code for online
}else{
// code for offline
}
}])
我打电话给'deviceready'事件检查,状态得到了。但我的问题是 - deviceready
在我的控制器启动后被调用。是否可以在角度控制器开始执行之前检查网络状态?< / p>
答案 0 :(得分:0)
在Angular中,控制器在应用程序的运行阶段期间执行。您可以在该运行阶段之前执行一些代码,也称为配置阶段。
你应该从角度阅读module documentation。
配置块 - 在提供程序注册和配置阶段执行。只有提供者和常量 可以注入配置块。这是为了防止 在服务完全之前意外实例化服务 构造
运行块 - 在创建注入器后执行并用于启动应用程序。只有实例和常量才可以 注入运行块。这是为了防止进一步的系统 应用程序运行时的配置。
在您的代码中,它应如下所示:
angular.module('myModule', []).
config(function(injectables) { // provider-injector
// This is an example of config block.
// You can have as many of these as you want.
// You can only inject Providers (not instances)
// into config blocks.
}).
run(function(injectables) { // instance-injector
// This is an example of a run block.
// You can have as many of these as you want.
// You can only inject instances (not Providers)
// into run blocks
});
不确定我是否理解,但这可能让您在运行控制器之前执行代码:)
考虑到你的代码......配置只会运行一次,你的连接会随着时间的推移而改变(如果在汽车中,从4G到3G)。因此可能需要检查或检查您的控制器。最佳情况可能是您在激活控制器时调用的功能。