Angularjs 无法从服务获取控制器中的数据
Angularjs 无法从服务获取控制器中的数据,angularjs,Angularjs,app.service('customersService',函数($http){ this.getCustomer=函数(id){ $http({ 方法:“GET”, url:“/getCustomer”, 参数:{id:id}, 标题:{'Content-Type':'application/x-www-form-urlencoded'}, }).成功(功能(数据){ 控制台日志(数据); 返回数据; }) }; });您只是忘记了返回$http承诺,这就是返回未定义的的原因。您需要执行以下
app.service('customersService',函数($http){
this.getCustomer=函数(id){
$http({
方法:“GET”,
url:“/getCustomer”,
参数:{id:id},
标题:{'Content-Type':'application/x-www-form-urlencoded'},
}).成功(功能(数据){
控制台日志(数据);
返回数据;
})
};
});
您只是忘记了返回$http承诺,这就是返回未定义的的原因。您需要执行以下操作:
...
return $http({ ...
您之所以会出现此错误,是因为您没有从$http
get请求返回承诺
按如下方式编辑代码:
app.service('customersService',函数($http){
this.getCustomer=函数(id){
返回$http({
方法:“GET”,
url:“/getCustomer”,
参数:{id:id},
标题:{'Content-Type':'application/x-www-form-urlencoded'},
});
};
});
然后在控制器中使用.then()
,处理响应数据
app.controller('myController', function($scope, customerService){
customersService.getCustomer(customerID)
.then(function(response){
$scope.data = response;
})
})
尝试给定的代码
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;
});
现在很好用。谢谢