无法从服务中获得的控制器中的数据
问题描述:
app.service('customersService', function ($http) {
this.getCustomer = function (id) {
$http({
method: 'GET',
url: '/getCustomer',
params: {id: id},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
}).success(function(data) {
console.log(data);
return data;
})
};
});
无法获得从服务 这段代码的问题控制器的数据是,当我尝试运行此
customersService.getCustomer(customerID).then
它生成下面提到一个错误:
angular.js:13294 TypeError: Cannot read property 'then' of undefined.
最主要的是对服务的调用被生成,如果我尝试在服务中的控制台上打印结果,数据就在那里。但是,我无法获取我的控制器中的数据。
答
您监守你不是从$http
GET请求返回的承诺得到这个错误。
编辑你的代码是这样的:
app.service('customersService', function ($http) {
this.getCustomer = function (id) {
return $http({
method: 'GET',
url: '/getCustomer',
params: {id: id},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
});
};
});
,然后在你的控制器.then()
,你处理响应数据。
app.controller('myController', function($scope, customerService){
customersService.getCustomer(customerID)
.then(function(response){
$scope.data = response;
})
})
答
您只需忘记返回$ http承诺,这就是为什么undefined
被返回。你需要做到以下几点:
...
return $http({ ...
答
尝试给定的代码。
app.service('customersService', function ($http) {
var getCustomer = function (id) {
return $http({
method: 'GET',
url: '/getCustomer',
params: {id: id},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
})
};
var customersService = {
getCustomer: getCustomer
}
return ProfileService;
});
现在工作非常好。谢谢 ! –