我是angularjs中的新成員,並且存在與angular中的工作同步問題。 這裏是我的代碼,要填寫的控制變量與溫控功能的結果,現在它返回一個空的對象或undfined:運行angularjs代碼同步併爲函數結果等待varibale
我想使用的服務和使用時,他們已經準備好結果的解決方案,又該我做?
App.service("UserService",['$location',"$http","$timeout",function($location,$http,$timeout){
var User={};
var CheckAuthenticationURL="/fa/home/IsAuthenticate";
if($location.protocol() == "https")
{
CheckAuthenticationURL="https://www.mytest.org/fa/home/IsAuthenticateSecure";
}
var UpdateUserData= function(){
return $http.get(CheckAuthenticationURL)
.success(function(data, status, headers, config) {
User=data;
})
};
var getUser= function()
{
UpdateUserData();
return User;
}
return{
UpdateUserData: UpdateUserData,
getUser: getUser
};
}]);
App.controller('GeneralCtrl',['$scope','$http','UserService','$interval', function($scope,$http,UserService,$interval) {
$scope.User={};
$scope.User=UserService.getUser();
}]);
'$ http.get'是異步的,你不能讓它變成同步的。你不應該試圖讓它變成同步,你應該等待UserService在使用之前被填充。你正在使用'angular-route','angular-route2'或'ui-router'嗎? – Camusensei
@Camusensei:那麼,它有什麼解決方案?它可以隨時有它,但是當頁面加載時,它將值設置爲未定義,並且在結果出現後沒有更新 –
不,我沒有使用它們中的任何一個 –