我正在尝试使用服务来获取用户的个人资料信息以显示在我的模板标题中。
问题是我的控制器中的变量在服务实际返回任何内容之前就已经设置好了(或者至少看起来像这样)。
app.js
// This gets the basic information that is needed for every page
myapp.service('base', function($http) {
this.getProfile = function() {
// Get the logge din users info
$http.get(baseUrl+'v1/users?api_key=1234')
.success(function(response) {
console.log('base response = '+response);
return response;
})
}
});
profile.js
myapp.controller('ProfileController', ['$scope', '$http', 'base', function($scope, $http, base) {
base.getAuthHeader();
$scope.profile = base.getProfile();
console.log('$scope.profile = '+$scope.profile);
}]);
在我的萤火虫中,这是按照这个确切顺序的输出:
$scope.profile = undefined
base repose = [object Object]
console.log('$scope.profile = '+$scope.profile);
之前如何调用console.log('base response = '+response);
行?
答案 0 :(得分:1)
您需要使用回调。
myapp.service('base', function($http) {
this.getProfile = function() {
// Get the logge din users info
$http.get(baseUrl+'v1/users?api_key=1234')
.success(function(response) {
// this code is async
// it wont fire as a part of the execution block
// but rather on its own once the `$http.get` returns
console.log('base response = '+response);
return response; // also this return returns
// the .success function not the .getProfile function
})
}
});
使用回调,您的代码看起来像这样:
myapp.service('base', function($http) {
// accept a function as an argument
this.getProfile = function(callback) {
// Get the logge din users info
$http.get(baseUrl+'v1/users?api_key=1234')
.success(function(response) {
console.log('base response = '+response);
// fire that function when response is available
callback(response);
})
}
});
然后在控制器中
myapp.controller('ProfileController', ['$scope', '$http', 'base', function($scope, $http, base) {
base.getAuthHeader();
base.getProfile(function(response){
$scope.profile = response;
console.log('$scope.profile = '+$scope.profile);
});
}]);
或者您可以使用promises而不是回调来处理异步性质。