本文介绍了在服务的角度$ HTTP,回报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个在我厂
productsFactory.getOneProduct = function(){
$http({
method: 'GET',
url: '/api/products/' + $stateParams.productID
}).
success(function(data, status, headers, config){
console.log(data);
return data;
}).
error(function(data, status, headers, config){
});
}
这是我的控制器:
$scope.selectedProduct = ProductsFactory.getOneProduct();
执行console.log(数据)输出我想要的数据。但我得到未定义当我打电话从控制器。猜猜它得到的东西做从匿名函数返回?我是不是做错了?
console.log(data) outputs the data i want. But I get 'undefined' when I call it from controller. Guess it got something to do with returning from anonymous functions? Am I doing it wrong?
推荐答案
您 getOneProduct
函数不返回任何东西,这意味着它含蓄地返回未定义
,因此错误。
Your getOneProduct
function does not return anything which means it implicitly returns undefined
, hence the error.
$ HTTP
返回一个承诺,你必须从你的函数返回的承诺。因此,改变你的code这样:
$http
returns a promise and you must return that promise from your function. So change your code to this:
productsFactory.getOneProduct = function(){
return $http({
method: 'GET',
url: '/api/products/' + $stateParams.productID
}).
success(function(data, status, headers, config){
console.log(data);
return data;
}).
error(function(data, status, headers, config){
});
}
然后在你的控制器:
Then in your controller:
productsFactory
.getOneProduct()
.then(response){});
这篇关于在服务的角度$ HTTP,回报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!