我正在尝试将数据从我的服务传递回我的 Controller ,但没有成功。我能够从 Controller 调用我的服务,并且我知道服务本身可以工作,因为我可以控制台记录服务内的响应(但不能返回 Controller )。
这是我的服务:
(function () {
angular
.module('app')
.service('testService', testService);
testService.$inject = ['$http'];
function testService($http, url) {
var baseUrl = "http://getjsondata.com/" + url;
this.getData = function (url) {
$http({
method: 'GET',
url: baseUrl + url,
headers: {'Content-Type': 'application/json'}
})
.then(function (response) {
console.log(response); // THIS WORKS
return response;
})
.catch(function (error) {
return error;
});
};
}
}());
这是在我的 Controller 内:
vm.getTestData = function (url) {
vm.response = testService.getData(url);
console.log(vm.response);
};
我尝试将数据作为 testService.getData 中的回调传递回来,但没有成功。我还尝试使用工厂而不是服务,但我无法访问 Controller 中的数据。我还尝试以不同的方式在服务中定义我的函数(getData:function()...)等等。
我猜我在服务中的返回语句的行为与我预期的不同。我将不胜感激任何帮助!
最佳答案
getData 永远不会返回。在 $http 前面添加 return 并在 Controller 中使用 .then 。
this.getData = function (url) {
return $http({
method: 'GET',
url: baseUrl + url,
headers: {'Content-Type': 'application/json'}
})
};
按ctrl键
vm.getTestData = function (url) {
testService.getData(url).then(function (response) {
vm.response = response;
return response;
})
.catch(function (error) {
return error;
});
};
关于javascript - 在 AngularJs 中使用服务通过 $http get 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48608430/