因为觉得factory是单例的所以把http结果作为factory的返回值,怎么做到在angular初始化时$http为factory赋初值?angular.module('some',[]) .factory('factory',function($http){ var some = {}; $http.get('url') .success(function(resp){ some.data = resp; }) return some.data; })
现在类似是这样写的,我就希望angular初始化的时候把从服务器取一些值之后可以一直用
You must have discovered that the problem with your writing is that data acquisition is asynchronous.
some.data
刚开始还是undefined
。但你的直觉是对的:通用的数据应当放在factory
或service
Inside. Now to solve the asynchronous problem, there are three solutions:Convert to sync. This is the most direct solution. Render the required data directly in the template on the server side, using the
factory
从HTML中取数据,一般用input
tag. Along this line of thinking, a better way is to set up the resources before starting the Angular App. You can refer to this article: http://harttle.github.io/2015/05/31/angular-scope-initialize.html#1Asynchronous callback. Use
factory
to return a callback function, written like this:Use Promise/Deffered mode for asynchronous operation. As projects become more and more complex,Promise is the ultimate solution. Angular provides an implementation of this pattern, which will return a Promise instance. Used like this:
$q
,它是一个Service,$http.get
angular.run(fn)
angularjs $http does not support synchronous acquisition
Want to initialize or output response.write from backend to frontend
Or use jquery's ajax blocking to get the data and then initialize angular
For routing, you can use resolve to inject controller
http://stackoverflow.com/questions/16286605/initialize-angularjs-servi...
There are thousands of initialization methods. The key is not whether the value you want is obtained synchronously or asynchronously, but where and when do you use it? Goal orientation determines what method you use for initialization. Of course using promises is recommended in most cases.