AngularJS - 如何将范围变量传递给服务?

时间:2015-09-03 16:56:08

标签: javascript angularjs angularjs-controller angularjs-factory angular-http

这是我的控制器,我在我的服务中使用了一个变量,以便从服务器访问一些JSON数据。

控制器中我的部分:

1)从服务器获取API密钥(工作并将密钥记录到控制台中):

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

2)想要将密钥传递给服务,以便访问数据:

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

服务:

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 是一个提供给我的号码,没错。 myWebsite.com 是一个网站示例,我想从中获取JSON数据。

那么,如何在不返回undefined的情况下将$ scope.apiKey传递给服务?

2 个答案:

答案 0 :(得分:2)

当你从DrawService.getData得到回复时,你需要调用AuthenticationService.getData()方法,这只是意味着你应该在apiKey

时调用DrawService方法
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);
     });
});

答案 1 :(得分:1)

所以要明确,你可以将$ scope变量传递给服务 - 这里的问题是你在从API返回API密钥之前尝试访问$ scope.apiKey验证服务。要确保在使用数据之前解决数据,只需在AuthenticationService的UINavigationBar内调用DrawService。