Angularjs同步操作http请求with $promise
// Define a factory
app.factory('profilePromise', ['$q', 'AccountService', function($q, AccountService) {
var deferred = $q.defer();
AccountService.getProfile().then(function(res) {
deferred.resolve(res);
}, function(res) {
deferred.resolve(res);
});
return deferred.promise;
}]);
// use a factory
// parent controller user
$scope.getPersonalInfo = function() {
profilePromise.then(function(res) {
var profile = res.content;
........
// define a scope used on child
$scope.profilePromise = profilePromise;原由:有时候在前端开发的时候,需要多次调用同一个http请求,若多次加载不仅不浪费不必要的http请求,还会多处代码维护,为开发带来诸多不变。
另一方面使用$boardcast父级发送消息数据给子级,子级经常会遇到异步操作无法正确获取需要的数据。
特此添加factory,一处添加维护,其他地方直接使用即可。
参考:http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/
若有疑问,请发表评论或添加微信为你解答:

更多实例应用扫码体验:

相关推荐
wanghongsha 2020-03-26
liduote 2020-06-16
阿斌Elements 2020-06-11
xxuncle 2020-06-05
ChinaGuanq 2020-06-05
csm0 2020-03-05
shyoushine 2020-02-25
electronvolt 2020-02-12
jsonwoo 2020-01-20
ZadarrienChina 2020-01-07
wwwxuewen 2020-01-04
dynsxyc 2020-01-03
liangjielaoshi 2019-12-27
bowean 2019-12-27
wwwxuewen 2019-12-25
liwusen 2019-12-16
颤抖吧腿子 2019-12-16