AngularJS:使用异步数据初始化服务

我有一个AngularJS服务,我想使用一些异步数据进行初始化。像这样:

myModule.service('MyService', function($http) {
    var myData = null;

    $http.get('data.json').success(function (data) {
        myData = data;
    });

    return {
        setData: function (data) {
            myData = data;
        },
        doStuff: function () {
            return myData.getSomeData();
        }
    };
});

显然,这是行不通的,因为如果doStuff()myData返回之前尝试调用某些方法,则会得到一个空指针异常。据我从阅读这里这里提出的其他一些问题中所知道的,我有一些选择,但是它们似乎都不是很干净(也许我错过了一些东西):

安装服务“运行”

设置我的应用时,请执行以下操作:

myApp.run(function ($http, MyService) {
    $http.get('data.json').success(function (data) {
        MyService.setData(data);
    });
});

然后我的服务将如下所示:

myModule.service('MyService', function() {
    var myData = null;
    return {
        setData: function (data) {
            myData = data;
        },
        doStuff: function () {
            return myData.getSomeData();
        }
    };
});

这有时会起作用,但是如果异步数据恰好比初始化所有东西花费的时间更长,则在我调用时会得到一个空指针异常 doStuff()

使用承诺对象

This would probably work. The only downside it everywhere I call MyService I will have to know that doStuff() returns a promise and all the code will have to us then to interact with the promise. I would rather just wait until myData is back before loading the my application.

Manual Bootstrap

angular.element(document).ready(function() {
    $.getJSON("data.json", function (data) {
       // can't initialize the data here because the service doesn't exist yet
       angular.bootstrap(document);
       // too late to initialize here because something may have already
       // tried to call doStuff() and would have got a null pointer exception
    });
});

Global Javascript Var I could send my JSON directly to a global Javascript variable:

HTML:

<script type="text/javascript" src="data.js"></script>

data.js:

var dataForMyService = { 
// myData here
};

Then it would be available when initializing MyService:

myModule.service('MyService', function() {
    var myData = dataForMyService;
    return {
        doStuff: function () {
            return myData.getSomeData();
        }
    };
});

This would work too, but then I have a global javascript variable which smells bad.

Are these my only options? Are one of these options better than the others? I know this is a pretty long question, but I wanted to show that I have tried to explore all my options. Any guidance would greatly be appreciated.

小宇宙飞云2020/03/12 20:40:47

另外,在执行实际的控制器之前,您可以使用以下技术在全球范围内配置服务:https : //stackoverflow.com/a/27050497/1056679只需全局解析您的数据,然后将其run例如块形式传递给您的服务