[英]Not able to retrieve the response from the angular js service
我编写了一个有角度的js服务,该服务返回响应。 但是,当我尝试从控制器调用服务时,我无法获得确切的响应。
app.service('testservice', function($http){
var details= {};
details.getResponse = function() {
return $http({
url: 'send/getdata',
method: 'GET'
}).success(function(data, status, headers, config) {
this.getdata = data;
return getdata;
});
};
return details;
});
我正在使用下面的控制器来调用该方法。
app.controller('testcontroller',[ '$scope', '$http','testService',function($scope, $http,testService) {
var targetresponse = testService.getResponse();
alert(JSON.stringify(targetresponse))
})]);
我收到以下响应,{“ $$ state”:{“ status”:0,“ pending”:[[{“ promise”:{“ $$ state”:{“ status”:0}}},null ,null,null]]}}
请让我知道这里的错误。
您的testservice
服务的getResponse
方法应该返回一个testservice
,您可以在控制器内继续该testservice
链。
服务
details.getResponse = function() {
return $http({
url: 'send/getdata',
method: 'GET'
}).then(function(res) {
this.getdata = res.data;
return res.data;
});
};
您可以使用承诺的resolve并在.then
函数中获取数据
var targetresponse = testService.getResponse();
targetresponse.then(function(data){
alert(JSON.stringify(data))
})
Srv.getData().then(function (success) {
var data = success.data;
$scope.myData = data;
}, function (error) {
});
最好的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.