angularjs离子和全局变量:使变量在全球范围内可用的最佳实践

时间:2022-12-18 23:01:05

I am new to Angular/Ionic. Before using Angular/Ionic, at the launch of my app, I was checking if we were under Phonegap or a browser using and storing this information in a global boolean variable and then checking if the app was online or offline and storing it to a global variable too, like this :

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

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;
}

Now I would like to do the same with Angular/Ionic, I understand that I have to use a "Service". But is it the best way to make this information available through all the code ?

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

I am doing the following, but is it the "best practice" ?

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

in index.html :

在index.html中:

<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>

in services.js :

在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;
    }

})

;

in app.js :

在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) {
//...
});

This works for now, but I need the boolean isPhoneGap to be available everywhere I need it (almost everywhere in my app).

这适用于现在,但我需要布尔值isPhoneGap在我需要的任何地方都可用(几乎在我的应用程序中的任何地方)。

Can you converge to the best practice to do this ?

你能收敛到最好的做法吗?

Thanks

谢谢

3 个解决方案

#1


10  

You should not set variables using $rootScope, and try to refrain from using $scope as much as possible. Using LocalStorage is okay, but this data will persist. I would recommend setting up a factory to store and retrieve variables using SessionStorage. SessionStorage is tied to the tab you have open, so the data is gone when it is closed.

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

This is one of my session storage services. I throw $cookieStorage in case local storage isn't available. Also, localStorage can only store strings. This is why you will see me converting objects and arrays to and from JSON as needed. After injecting sessionService, I need only call sessionService.store(name, data) to store a session variable or sessionService.persist(name, data) to store persistent data i.e. userName if "Remember Me" is checked. :

这是我的会话存储服务之一。我抛出$ cookie存储以防本地存储不可用。此外,localStorage只能存储字符串。这就是为什么你会看到我根据需要在JSON之间转换对象和数组的原因。注入sessionService之后,我只需调用sessionService.store(name,data)来存储会话变量或sessionService.persist(name,data)来存储持久数据,即如果选中“Remember Me”则存在userName。 :

.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 is part of ngCookies. Make sure you have angular-cookies.js included and load ngCookies as you would any module. Angular ngCookies

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

#2


3  

First off, I'm pretty new to both Ionic and Angular, however I had the same problem with my web app Angular and I have done following to get it working

首先,我对Ionic和Angular都很陌生,但是我的网络应用程序Angular遇到了同样的问题,我已经完成了以下工作以使其正常工作

  1. assign variables to $rootScope, that way it's visible to all the controllers

    将变量分配给$ rootScope,这样所有控制器都可以看到它

  2. assign variables to $scope , which is visible by current context. Ex: controller and the html pages uses that controller

    将变量分配给$ scope,这是当前上下文可见的。例如:控制器和html页面使用该控制器

  3. localStorageService, because this will hold the values even after user refreshes the page.

    localStorageService,因为即使用户刷新页面,它也会保留值。

Again please note, this is what I did in my Angular web app and might not be the best practices, but I hope you get the idea.

请再次注意,这是我在Angular Web应用程序中所做的,可能不是最好的做法,但我希望你明白这个想法。

#3


0  

There are methods available in ionic.Platform that assist in getting back the data you need in regards to the device type.

ionic.Platform中提供了一些方法,可帮助您获取有关设备类型的所需数据。

http://ionicframework.com/docs/api/utility/ionic.Platform/

http://ionicframework.com/docs/api/utility/ionic.Platform/

You could alternatively look at adding ngCordova, which has a bunch of useful wrappers around cordova plugins, including the device plugin.

您也可以考虑添加ngCordova,它包含一些围绕cordova插件的有用包装器,包括设备插件。

http://ngcordova.com/docs/#Device

http://ngcordova.com/docs/#Device

#1


10  

You should not set variables using $rootScope, and try to refrain from using $scope as much as possible. Using LocalStorage is okay, but this data will persist. I would recommend setting up a factory to store and retrieve variables using SessionStorage. SessionStorage is tied to the tab you have open, so the data is gone when it is closed.

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

This is one of my session storage services. I throw $cookieStorage in case local storage isn't available. Also, localStorage can only store strings. This is why you will see me converting objects and arrays to and from JSON as needed. After injecting sessionService, I need only call sessionService.store(name, data) to store a session variable or sessionService.persist(name, data) to store persistent data i.e. userName if "Remember Me" is checked. :

这是我的会话存储服务之一。我抛出$ cookie存储以防本地存储不可用。此外,localStorage只能存储字符串。这就是为什么你会看到我根据需要在JSON之间转换对象和数组的原因。注入sessionService之后,我只需调用sessionService.store(name,data)来存储会话变量或sessionService.persist(name,data)来存储持久数据,即如果选中“Remember Me”则存在userName。 :

.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 is part of ngCookies. Make sure you have angular-cookies.js included and load ngCookies as you would any module. Angular ngCookies

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

#2


3  

First off, I'm pretty new to both Ionic and Angular, however I had the same problem with my web app Angular and I have done following to get it working

首先,我对Ionic和Angular都很陌生,但是我的网络应用程序Angular遇到了同样的问题,我已经完成了以下工作以使其正常工作

  1. assign variables to $rootScope, that way it's visible to all the controllers

    将变量分配给$ rootScope,这样所有控制器都可以看到它

  2. assign variables to $scope , which is visible by current context. Ex: controller and the html pages uses that controller

    将变量分配给$ scope,这是当前上下文可见的。例如:控制器和html页面使用该控制器

  3. localStorageService, because this will hold the values even after user refreshes the page.

    localStorageService,因为即使用户刷新页面,它也会保留值。

Again please note, this is what I did in my Angular web app and might not be the best practices, but I hope you get the idea.

请再次注意,这是我在Angular Web应用程序中所做的,可能不是最好的做法,但我希望你明白这个想法。

#3


0  

There are methods available in ionic.Platform that assist in getting back the data you need in regards to the device type.

ionic.Platform中提供了一些方法,可帮助您获取有关设备类型的所需数据。

http://ionicframework.com/docs/api/utility/ionic.Platform/

http://ionicframework.com/docs/api/utility/ionic.Platform/

You could alternatively look at adding ngCordova, which has a bunch of useful wrappers around cordova plugins, including the device plugin.

您也可以考虑添加ngCordova,它包含一些围绕cordova插件的有用包装器,包括设备插件。

http://ngcordova.com/docs/#Device

http://ngcordova.com/docs/#Device