[英]How to make http call in service but get response by the controller? AngularJS
我有一个叫http的服务,问题是我不了解如何在控制器中使用$ scope.photos。如何配置控制器和服务来做到这一点?
app.service('http',function($scope,$http){
function getAll() {
$http.get('/allphotos').then(function success(response) {
$scope.photos = response.data;
}, function error(err) {
console.log('error is:' + err.err)
});
}
});
app.controller('ctrl',function ($scope, http) {
}
首先,永远不要在Service / Factory / Provider内部使用$scope
。 范围仅与控制器有关,ae处理与控制器的绑定视图。
您有一个应返回Promise的getAll()
方法,您将能够在控制器内部对其进行解析。
就像是:
app.service('httpService',function(,$http){
this.getAll = function() {
return $http.get('/allphotos').then(function(response) {
// ^ 'getAll' returns Original Promis comes from '$http'
return response.data;
// ^ here we resolve 'response.data'
}, function(err) {
console.log('error is:' + err.err)
});
}
});
现在在控制器中执行以下操作:
app.controller('ctrl',function ($scope, httpService) {
httpService.getAll().then(function(data) {
$scope.data = data;
}, function error(err) {
console.log('error is:' + err.err)
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.