javascript-AngularJS $http数据未正确返回
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript-AngularJS $http数据未正确返回,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1801字,纯文字阅读大概需要3分钟。
内容图文
![javascript-AngularJS $http数据未正确返回](/upload/InfoBanner/zyjiaocheng/680/548990c4a1f6457da9b65d79b66acb0e.jpg)
这个问题已经在这里有了答案: > How do I return the response from an asynchronous call? 34个
我正在尝试封装数据(通过JSON文件),以使用工厂在控制器之间使用,尽管当我调用工厂时,它在返回数据之前执行$scope,导致数组为空.
我希望能够首先获取数据,然后执行返回我的数据的$scope声明,例如:
厂:
angular.module('myApp')
.factory('StoreProducts', function ($http) {
var storeData = [];
var promise = $http.get('/example.json')
.success(function (data) {
storeData = data;
});
return {
promise: promise,
setData: function(data) {
storeData = data;
},
getData: function() {
return storeData;
}
};
});
控制器:
angular.module('myApp')
.controller('StoreCtrl', function ($scope, $log, StoreProducts) {
$scope.data = StoreProducts.getData();
$log.log($scope.data);
});
JSON文件:
[
{
"productId": "1",
"name": "Example 1",
"price": "5.99"
},
{
"productId": "2",
"name": "Example 2",
"price": "2.99"
},
]
我认为这是因为getData()函数的范围已完全关闭,但是,我似乎认为并非如此.我到底在做什么错?
解决方法:
通常,您的数据函数将返回一个Promise对象.从概念的角度来看,如果您处理诸如数据检索之类的异步操作,则getData不能(也不应)简单地返回值,而是一个承诺.
基本思想是这样的:
angular.module('myApp')
.factory('StoreProducts', function ($http) {
// ...
return {
// ...
getData: function() {
return $http.get('/example.json').then(function(response) {
return response.data;
});
}
};
});
稍后在控制器中使用:
StoreProducts.getData().then(function(data) {
$scope.data = data;
});
当然,如果您不想在每个getData调用中查询服务器,则可以添加缓存层.如果缓存的值可用,则再次返回promise,但是这次promise将立即解决而不发出请求:
getData: function() {
return storeData ? $q.when(storeData) : $http.get('/example.json').then(function(response) {
storeData = response.data;
return storeData;
})
}
演示:http://plnkr.co/edit/bM6AK5sEQ5ZEEad4BVUu?p=preview
内容总结
以上是互联网集市为您收集整理的javascript-AngularJS $http数据未正确返回全部内容,希望文章能够帮你解决javascript-AngularJS $http数据未正确返回所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。