本文翻译自:AngularJS : Initialize service with asynchronous data
I have an AngularJS service that I want to initialize with some asynchronous data. 我有一个AngularJS服务,我想用一些异步数据进行初始化。 Something like this: 像这样的东西:
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();
}
};
});
Obviously this won't work because if something tries to call doStuff()
before myData
gets back I will get a null pointer exception. 显然这不起作用,因为如果某些东西试图在myData
返回之前调用doStuff()
,我将得到一个空指针异常。 As far as I can tell from reading some of the other questions asked here and here I have a few options, but none of them seem very clean (perhaps I am missing something): 据我所知,从这里和这里提出的其他一些问题,我有几个选择,但没有一个看起来很干净(也许我错过了一些东西):
Setup Service with "run" 使用“运行”设置服务
When setting up my app do this: 设置我的应用时,请执行以下操作:
myApp.run(function ($http, MyService) {
$http.get('data.json').success(function (data) {
MyService.setData(data);
});
});
Then my service would look like this: 然后我的服务看起来像这样:
myModule.service('MyService', function() {
var myData = null;
return {
setData: function (data) {
myData = data;
},
doStuff: function () {
return myData.getSomeData();
}
};
});
This works some of the time but if the asynchronous data happens to take longer than it takes for everything to get initialized I get a null pointer exception when I call doStuff()
这种情况在某些时候有效,但是如果异步数据发生的时间比初始化所有内容要花费的时间长,那么当我调用doStuff()
时会得到一个空指针异常
Use promise objects 使用promise对象
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. 我称之为MyService的唯一缺点就是我必须知道doStuff()会返回一个promise, then
我们需要所有代码与promise进行交互。 I would rather just wait until myData is back before loading the my application. 在加载我的应用程序之前,我宁愿等到myData返回。
Manual Bootstrap 手动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: 全局Javascript Var我可以将我的JSON直接发送到全局Javascript变量:
HTML: HTML:
<script type="text/javascript" src="data.js"></script>
data.js: data.js:
var dataForMyService = {
// myData here
};
Then it would be available when initializing MyService
: 然后在初始化MySer