gpt4 book ai didi

angularjs ionic 和全局变量 : best practice to make a variable available globally

转载 作者:行者123 更新时间:2023-12-03 16:54:16 31 4
gpt4 key购买 nike

我是 Angular/Ionic 的新手。
在使用 Angular/Ionic 之前,在我的应用程序启动时,我正在检查我们是否在 Phonegap 或浏览器下使用并将此信息存储在全局 bool 变量中,然后检查应用程序是在线还是离线并将其存储到全局变量也一样,像这样:

var isPhoneGap;
var connectionStatus;
isPhoneGap = checkIfPhoneGap();

//later in the code :

connectionStatus = checkIfOnline();

function checkIfPhoneGap() {
var app = document.URL.indexOf( 'http://' ) === -1 && document.URL.indexOf( 'https://' ) === -1; // && document.URL.indexOf( 'file://' );
if ( app ) {
return true;
} else {
return false;
}
}
function checkIfOnline() {
if ( isPhoneGap ) {
if (checkConnection() == "none" ) {
connectionStatus = 'offline';
} else {
connectionStatus = 'online';
}
function checkConnection() {
var networkState = navigator.network.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.NONE] = 'No network connection';
//console.log('Connection : ' + Connection);
//console.log('Connection type: ' + states[networkState]);
return networkState;
}
} else {
connectionStatus = navigator.onLine ? 'online' : 'offline';
}
return connectionStatus;
}

现在我想对 Angular/Ionic 做同样的事情,我知道我必须使用“服务”。但这是通过所有代码提供此信息的最佳方式吗?

我正在做以下事情,但这是“最佳实践”吗?

在 index.html 中:
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>

在 services.js 中:
angular.module('SnowBoard.services', [])

.factory('isPhoneGap', function() {

var appp = document.URL.indexOf( 'http://' ) === -1 && document.URL.indexOf( 'https://' ) === -1; // && document.URL.indexOf( 'file://' );
if ( appp ) {
return true;
} else {
return false;
}

})

;

在 app.js 中:
angular.module('SnowBoard', ['ionic', 'SnowBoard.controllers', 'SnowBoard.services'])

.run(["isPhoneGap","$ionicPlatform", function(isPhoneGap, $ionicPlatform) {
$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.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});

//CHECK IF ONLINE
connectionStatus = checkIfOnline(isPhoneGap);

//DEBUG
//var debugOptionUseLocalDB=0;
//updateProDB(connectionStatus, debugOptionUseLocalDB);
}])
.config(function($stateProvider, $urlRouterProvider) {
//...all state configurations
})
.config(function($stateProvider, $urlRouterProvider) {
//...
});

这暂时有效,但我需要 bool 值 isPhoneGap随时随地可用(在我的应用程序中几乎无处不在)。

你能收敛到最佳实践来做到这一点吗?

谢谢

最佳答案

您不应该使用 $rootScope 设置变量, 并尽量避免使用 $scope越多越好。使用 LocalStorage没关系,但这些数据会持续存在。我建议使用 SessionStorage 设置工厂来存储和检索变量. SessionStorage与您打开的选项卡相关联,因此关闭时数据将消失。

这是我的 session 存储服务之一。我扔$cookieStorage以防本地存储不可用。此外,localStorage 只能存储字符串。这就是为什么您会看到我根据需要在 JSON 之间转换对象和数组。注入(inject)后sessionService ,我只需要调用sessionService.store(name, data)存储 session 变量或 sessionService.persist(name, data)如果选中“记住我”,则存储持久数据,即用户名。 :

.service('sessionService', ['$cookieStore', function ($cookieStore) {
var localStoreAvailable = typeof (Storage) !== "undefined";
this.store = function (name, details) {
if (localStoreAvailable) {
if (angular.isUndefined(details)) {
details = null;
} else if (angular.isObject(details) || angular.isArray(details) || angular.isNumber(+details || details)) {
details = angular.toJson(details);
};
sessionStorage.setItem(name, details);
} else {
$cookieStore.put(name, details);
};
};

this.persist = function(name, details) {
if (localStoreAvailable) {
if (angular.isUndefined(details)) {
details = null;
} else if (angular.isObject(details) || angular.isArray(details) || angular.isNumber(+details || details)) {
details = angular.toJson(details);
};
localStorage.setItem(name, details);
} else {
$cookieStore.put(name, details);
}
};

this.get = function (name) {
if (localStoreAvailable) {
return getItem(name);
} else {
return $cookieStore.get(name);
}
};

this.destroy = function (name) {
if (localStoreAvailable) {
localStorage.removeItem(name);
sessionStorage.removeItem(name);
} else {
$cookieStore.remove(name);
};
};

var getItem = function (name) {
var data;
var localData = localStorage.getItem(name);
var sessionData = sessionStorage.getItem(name);

if (sessionData) {
data = sessionData;
} else if (localData) {
data = localData;
} else {
return null;
}

if (data === '[object Object]') { return null; };
if (!data.length || data === 'null') { return null; };

if (data.charAt(0) === "{" || data.charAt(0) === "[" || angular.isNumber(data)) {
return angular.fromJson(data);
};

return data;
};

return this;
}])

$cookieStore 是 ngCookies 的一部分。确保包含 angular-cookies.js 并像加载任何模块一样加载 ngCookies。 Angular ngCookies

关于angularjs ionic 和全局变量 : best practice to make a variable available globally,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27094272/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com