2

I have the following example code in my learning app. The service does his job and pulls some data out of a page with json code generated by php, so far so good.

service:

(function() {
    'use strict';

    angular
        .module('app.data')
        .service('DashboardService', DashboardService);

    DashboardService.$inject = ['$http'];
    function DashboardService($http) {

        this.getFormules = getFormules;

        ////////////////

        function getFormules(onReady, onError) {
            var formJson = 'server/php/get-formules.php',
                formURL  = formJson + '?v=' + (new Date().getTime()); // Disables cash

            onError = onError || function() { alert('Failure loading menu'); };

            $http
                .get(formURL)
                .then(onReady, onError);
        }

    }
})();

Then i call the getFormules function in my controller and put all the data inside my $scope.formuleItems and test if everything succeeded and 'o no'... $scope.formuleItems = undefined! - Strange because my view is showing data?

part of the controller:

    dataLoader.getFormules(function (items){

        $scope.formuleItems = items.data;

    });

    console.log('+++++++++++++++++', $scope.formuleItems); // gives undefined

The first thing i did was search around on stackoverflow to look if someone else had the same issue, and there was: Undefined variable inside controller function.

I know there are some walkarounds for this, i've done my own research, but something tells me that this (see example below) isn't the best way to solve this problem.

solution one: put $watch inside of the controller

$scope.$watch('formuleItems', function(checkValue) {
   if (checkValue !== undefined) {
     //put the code in here!
  }
}

or even:

if($scope.formuleItems != null) {}

The rest of the controller is relying on $scope.formuleItems. Do i really have to put everything into that $watch or if? Can i fix this with a promise? I never did that before so some help would be appreciated.

Community
  • 1
  • 1
Peter
  • 1,240
  • 2
  • 13
  • 22
  • Javascript is run asynchronous. How do you know that your function that sets that value is running before your log to the console? There's a good question that covers that but I can't find it currently. However that's what you need to read up on. Found it: http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Matthew Green Jan 07 '16 at 16:38
  • 3
    I suggest you read http://blog.ninja-squad.com/2015/05/28/angularjs-promises/, which describes, among others, the two traps about angular promises that you fell into: not understanding asynchronism, and passing callback functions instead of not passing anything and returning a promise. – JB Nizet Jan 07 '16 at 16:52
  • Wow, JB Nizet, what a tutorial! lets keep this one close and read it some times till i really understand. – Peter Jan 08 '16 at 07:47

1 Answers1

1

The code in your callback

function (items){
    $scope.formuleItems = items.data;
}

is evaluated asynchronously. That means you first fire the request, then javascript keeps on executing your lines of code, hence performs

console.log('+++++++++++++++++', $scope.formuleItems); // gives undefined

At this point the callback was not invoked yet, because this takes some time and can happen at any point. The execution is not stopped for this. Therefore the value of $scope.formuleItems is still undefined, of course.

After that - at some not defined time in the future (probably a few milliseconds later) the callback will be invoked and the value of $scope.formuleItems will be changed. You have to log the value INSIDE of your callback-function.

You urgently have to understand this concept if you want to succeed in JavaScript, because this happens over and over again :)

Patrick Kelleter
  • 2,631
  • 1
  • 13
  • 19