bltzrrr
bltzrrr

Reputation: 809

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?

Upvotes: 1

Views: 204

Answers (2)

Dan Keiger
Dan Keiger

Reputation: 671

So to be clear, you can pass $scope variables to services - the issue here is you're trying to access $scope.apiKey before the APIkey is being returned to you from the Authentication Service. To ensure the data is resolved before using it, simply call your DrawService within the .then() of your AuthenticationService.

Upvotes: 1

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

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);
     });
});

Upvotes: 2

Related Questions