Search code examples
javascriptangularjsangularjs-controllerangularjs-factoryangular-http

AngularJS - how to pass a scope variable to a service?


This is my controller, in which I have a variable that I want to use in my service, in order to access some JSON data from the server.

Parts of the controller where I:

1) get the API key from the server (works and logs a key into the console):

AuthenticationService.getData()
        .then(function(result) {
            $scope.apiKey = result;
            console.log($scope.apiKey);
    });

2) Want to pass the key to service, in order to access data:

 DrawService.getData($scope.apiKey)
    .then(function(result) {
        $scope.numbers = result.data;
        console.log($scope.numbers);
}); 

Services:

app.factory('AuthenticationService', function($http) {
        return {
        getData: function() {
            return $http.get('http://game.mywebsite.com/start/?token=someNumber&sessionId=someNumber')
                .then(function(result) {
                    return result.data;
            }
        );
    }
}


app.factory('DrawService', function($http) {
            return {
                getData: function(apiKey) {
                var key = apiKey;
                console.log(key);    
                return $http.get('http://game.mywebsite.com/draw/?token='+apiKey)
                    .then(function(result) {
                        return result.data;
            });
        }
    }

someNumber is a number that was provided to me, no mistake there. myWebsite.com is a website example from where I want to get the JSON data.

So, how can I pass the $scope.apiKey to the service without it returning undefined?


Solution

  • You need to call DrawService.getData method when you get response from the AuthenticationService.getData(), That simply means that you should call the DrawService method when you have apiKey

    AuthenticationService.getData()
      .then(function(result) {
        $scope.apiKey = result;
        console.log($scope.apiKey);
         DrawService.getData($scope.apiKey)
           .then(function(result) {
             $scope.numbers = result.data;
             console.log($scope.numbers);
         });
    });