因?yàn)橛X得factory是單例的所以把http結(jié)果作為factory的返回值,怎么做到在angular初始化時(shí)$http為factory賦初值?angular.module('some',[])
.factory('factory',function($http){
var some = {};
$http.get('url')
.success(function(resp){
some.data = resp;
})
return some.data;
})
現(xiàn)在類似是這樣寫的,我就希望angular初始化的時(shí)候把從服務(wù)器取一些值之后可以一直用
想必你也發(fā)現(xiàn)了,你這樣寫的問題在于數(shù)據(jù)獲取是異步的。some.data
剛開始還是undefined
。但你的直覺是對的:通用的數(shù)據(jù)應(yīng)當(dāng)放在factory
或service
里面。現(xiàn)在來解決異步的問題,有三種方案:
轉(zhuǎn)化為同步。這是最直接的方案,把需要的數(shù)據(jù)在服務(wù)器端直接渲染在模板里,factory
從HTML中取數(shù)據(jù),一般用input
標(biāo)簽。沿著這個(gè)思路,更好的辦法是在啟動(dòng)Angular App前設(shè)置好資源。可以參考這篇文章: http://harttle.github.io/2015/05/31/angular-scope-initialize.html#1
異步回調(diào)。用factory
返回一個(gè)回調(diào)函數(shù),這樣寫:
javascript
xxx.factory('some', function($http){ var some = {} function get(cb){ if(some.data) return cb(some.data); $http.get('').success(function(d){ cb(some.data = d); }); } return get; }); ... some.get(function(data){ console.log(data); });
使用Promise/Deffered模式來進(jìn)行異步。隨著項(xiàng)目越來越復(fù)雜,Promise是最終解決方案。Angular提供了該模式的實(shí)現(xiàn)$q
,它是一個(gè)Service,$http.get
便會(huì)返回一個(gè)Promise的實(shí)例。這樣用的:
javascript
xxx.factory('some', function($q, $http){ return $http.get(''); }); ... some.success(function(data){ console.log(data); });
angularjs $http不支持同步獲取
想要初始化要么從后端response.write輸出到前端
要么用jquery的ajax阻塞獲取到data后再初始化angular
路由的話 可以用resolve注入controller
http://stackoverflow.com/questions/16286605/initialize-angularjs-servi...
初始化的方法千千萬,關(guān)鍵不在于你要的值是同步獲取還是異步獲取,而是你在哪里用,何時(shí)用?目標(biāo)導(dǎo)向決定你使用什么方法初始化。當(dāng)然在大多數(shù)情況下推薦使用 promise。