Search code examples
angularjsangularjs-scopeangular-promise

AngularJS $http response


here is my code

var object = null
app.controller("controller",function($scope,service){
    $scope.search=function(){
        service.findData().then(
            function successCallback(response){
                object = response.data
            },
            function errorCallback(response){
                alert("error")
            }
        )
        console.log(object)
    }
})

when I print the object, it is null so the question is: how can I get response.data outside?

Thank you for helping!


Solution

  • It was a general practice during the era of AngularJS to assign the controller to variable.

    app.controller("controller",function($scope,service){
        var self = this;
        $scope.search=function(){
            service.findData().then(
                function successCallback(response){
                    self.yourBusinessFunction (response.data)
    
                },
                function errorCallback(response){
                    alert("error")
                }
            )
            console.log(object)
        }
    
        self.yourBusinessFunction = function(data){
    
        console.log(data);
        // data here will be the response.data from the service
        // You can write your logic here
    
        }
    
    
    })