0

I have a controller and I make an http request to get some data. Data arrives but when I try to use it it's like it does not exist at all. I have used the same method in a previous project and everything worked well. I have been trying to fix this for a couple days but no luck. It seems like there is a problem with the scope or the order of execution is not the right one.

Here is my code:

  .controller("myCtrl", ['$scope', '$http', function($scope, $http) {
    console.log("myCtrl");

    var vm = this;

    $http.get('/get-data').then(function(response) {
      vm.data = JSON.stringify(response.data);
      console.log(vm.data); //returns correct json data
    })

    console.log(vm.data); //returns undefined

  }])

Further information: There are multiple controllers in the module.

Fotis Papadamis
  • 184
  • 3
  • 14
  • 3
    The second `console.log` logs `undefined` *before* the first `console.log` logs the result, right?! *That* is your problem. Timing! Not scope. – deceze Oct 26 '18 at 12:43
  • 1
    It's an asynchronous callback, keep your entire logic inside `.then()` – Aleksey Solovey Oct 26 '18 at 12:44
  • I can't keep my entire logic inside .then() I have to bind the results to the interface – Fotis Papadamis Oct 26 '18 at 12:54
  • @FotisPapadamis you are already binding it to `$scope.data`, so you can show it in HTML correctly, but if you need to use it in the controller, then all of your logic has to be within `.then()`. You can trick it, and make it synchronous with a **resolve** in app.config, if you have `ngRoute` or `ui.router`for routing. – Aleksey Solovey Oct 26 '18 at 13:01
  • First console.log is within asynchronous call which means in this scenario it will always be returned after the second console.log because first one takes a bit longer to be displayed. – LazioTibijczyk Oct 26 '18 at 15:45

0 Answers0