0

I wrote a angular js service which returns the response. But when I tried to call the service from the controller I am not able to get the 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 am using the below controller to call the method.

app.controller('testcontroller',[ '$scope', '$http','testService',function($scope, $http,testService) {
        var targetresponse = testService.getResponse();
        alert(JSON.stringify(targetresponse))
  })]);

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

Kindly, let me know the error here.

2 Answers 2

2

Your testservice service getResponse method should return a promise, and you can continue that promise chain inside your 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 that promise and get access of data inside .then function

var targetresponse = testService.getResponse();
targetresponse.then(function(data){
   alert(JSON.stringify(data))
})
Sign up to request clarification or add additional context in comments.

Comments

0
Srv.getData().then(function (success) {
        var data = success.data;
        $scope.myData = data;
    }, function (error) {
    });

Best way to to this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.