這是我的控制器,其中我有一個變量,我想在我的服務中使用,以便從服務器訪問一些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?
太棒了!訣竅! – bltzrrr
@bltzrrr高興地幫助你...謝謝:) –