Search code examples
angularjsangularjs-serviceangular-promise

console service response inside controller


i have written a service with take parameter on the basis of which it response me with the response of http request.

    this.getPaymentDueDetails=function(date){
    this.getfromRemote('paymentdue/'+btoa(date))
    .success(function(response){
        return response;
    })
    .error(function(response){
        return false;
    })
}

getfromRemote is my another service which make http request

now i am trying to get the response of this service call inside my controller function

 $scope.callDueReports=function(blockNum){
       var data;
       data=myAngService.getPaymentDueDetails('2015-04-20');
console.log(data);
        }

its quite obvious that i wont get any thing in data as the page loads initially but i want the result of getPaymentDueDetails int it.


Solution

  • Please modify your service to return the promise like below.

    this.getPaymentDueDetails = function(date) {
        return this.getfromRemote('paymentdue/' + btoa(date));
    };
    

    And in controller check if the promise is resolved.

    $scope.callDueReports = function(blockNum) {
        var data;
    
        myAngService.getPaymentDueDetails('2015-04-20').then(function(dataFromService) {
                data = dataFromService;
                console.log(data);
            })
            .catch(function(response) {
                console.error('error');
            });
    };