javascript - Not able to retrieve the response from the angular js service -


i wrote angular js service returns response. when tried call service controller not able exact response.

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; 

});

i using below controller call method.

app.controller('testcontroller',[ '$scope', '$http','testservice',function($scope, $http,testservice) {         var targetresponse = testservice.getresponse();         alert(json.stringify(targetresponse))   })]); 

i getting below response, {"$$state":{"status":0,"pending":[[{"promise":{"$$state":{"status":0}}},null,null,null]]}}

kindly, let me know error here.

your testservice service getresponse method should return promise, , can continue promise chain inside controller.

service

details.getresponse = function() {     return $http({         url: 'send/getdata',         method: 'get'     }).then(function(res) {         this.getdata = res.data;         return res.data;     }); }; 

you can use resolve promise , access of data inside .then function

var targetresponse = testservice.getresponse(); targetresponse.then(function(data){    alert(json.stringify(data)) }) 

Comments