AngularJS / Cordova:如何在设备准备后获得我工厂的价值?

时间:2015-11-03 16:54:39

标签: javascript html angularjs cordova angularjs-factory

我正在尝试使用Cordova设备插件来获取有关用户正在使用的设备的信息。文档说它只能在deviceready函数之后调用,所以在我的.run函数中我有以下内容:

.run(function($rootScope, $state, $stateParams) {

    document.addEventListener('deviceready', onDeviceReady, false);

    function onDeviceReady() {
        console.log(device);
    }

 //more functions below

这很好用,我在控制台中看到设备对象,但我真正想要的是在工厂内使用设备对象,有时会在deviceready事件之前调用它。

所以我的问题是,当工厂变得可用时,如何让make device对象可用?我想要类似下面的代码

angular.module('myapp.services.myFactory', [])

.factory('MyFactory', function($q) {

    function getDevice () {
        //if the deviceready event happend and I can access the device object set to variable
        return device;
    }

    return {
        getDeviceInfo: function getDeviceInfo() {
            return $q(function(resolve, reject) {
                if (getDevice()) {
                    //do something with the device object 
                } else {
                   //do something without device object
                }
            });
        }
    };
});

1 个答案:

答案 0 :(得分:0)

无需在此处使用.run - 您应该能够执行deviceready内的所有内容,包括您的模块和工厂定义。只需将此事件包装好即可。我也不相信你需要$q来解决任何承诺。请注意以下简化模式...

function onDeviceReady() {
    // guessing your dependency architecture
    angular
        .module('myapp', ['myapp.services'])
        .module('myapp.services', ['myapp.services.myFactory'])
        .module('myapp.services.myFactory', [])
        .factory('MyFactory', function() {

            function withDevice() {
                /*...*/
            }

            function withoutDevice() {
                /*...*/
            }

            return {
                // turnary. device always available to examine at this point
                'getDeviceInfo': device ? withDevice : withoutDevice
            }
        });
}

document.addEventListener('deviceready', onDeviceReady, false);