1

這是我的控制器,其中我有一個變量,我想在我的服務中使用,以便從服務器訪問一些JSON數據。AngularJS - 如何將範圍變量傳遞給服務?

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數據的網站示例。

那麼,如何將$ scope.apiKey傳遞給服務而不返回undefined?

回答

2

你需要調用DrawService.getData方法,當你從AuthenticationService.getData()響應,這只是意味着你應該調用DrawService方法,當你有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); 
    }); 
}); 
+0

太棒了!訣竅! – bltzrrr

+0

@bltzrrr高興地幫助你...謝謝:) –

1

所以要清楚,你可以通$範圍變量到服務 - 這裏的問題是,您正試圖訪問$ scope.apiKey,然後將APIkey從身份驗證服務返回給您。爲確保數據在使用前得到解決,只需在您的AuthenticationService的.then()內調用您的DrawService。