2

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!

p u
  • 1,395
  • 1
  • 17
  • 30
J.Smith
  • 23
  • 2
  • 2
    write `console.log` inside your success callback. You are working with Promises, you can't get the data out. You can assign it to a scoped variable with `$scope.object = ...` and then display it with `{{object}}` for example – Aleksey Solovey Nov 22 '18 at 13:22
  • 1
    yep,i know $scope.object can work,but i want this object to do other things in controller ,so i want to use object out of findData() – J.Smith Nov 22 '18 at 13:28
  • 1
    then you have to keep your entire logic inside that success callback. Or you can return the Promise, but if you want any data from it, you would need to resolve it every time with `.then` and still keep the logic inside the Promise – Aleksey Solovey Nov 22 '18 at 13:34
  • @AlekseySolovey I dont think doing the logic inside a sucesscallback is a good option. You can make a reference to the controller and write a controller function as done below in my answer. – Jins Peter Nov 22 '18 at 13:45

1 Answers1

2

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

    }


})
Jins Peter
  • 2,368
  • 1
  • 18
  • 37