[英]AngularJS - how to pass a scope variable to a service?
這是我的控制器,我有一個我想在我的服務中使用的變量,以便從服務器訪問一些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數據。
那么,如何將$ scope.apiKey傳遞給服務而不返回undefined?
當你從AuthenticationService.getData()
得到響應時,你需要調用DrawService.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);
});
});
因此,要清楚,您可以將$ scope變量傳遞給服務 - 這里的問題是您在從Authentication Service返回API密鑰之前嘗試訪問$ scope.apiKey。 要確保在使用數據之前解決數據,只需在AuthenticationService的.then .then()
內調用DrawService即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.