Angularjs 控制器在服务方法返回之前从服务中分配变量
Angularjs controller assigning variable from service, before service method returns
>我正在尝试使用服务来获取用户的个人资料信息,以显示在模板的标题中。
问题是我在控制器中的变量是在服务实际返回任何内容之前设置的(或者至少看起来是这样)。
应用.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;
})
}
});
简介.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);
之前是如何被调用的?
你需要使用回调。
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);
});
}]);
或者你可以用承诺而不是回调来处理异步性质。
相关文章:
- 如何将HTML id分配给元素,以及如何将JavaScript应用于元素
- 如何使用WCF服务和javascript表单post上传.doc文件
- 在循环中分配json值时,值被覆盖
- 动态分配GA增强型电子商务跟踪器
- 监视函数从服务返回不起作用,但作用域函数起作用
- 将jsp文件下拉列表中的选定项分配给一个java变量(比如String selection)
- 通过Magento的网络服务检索运费
- 如何在jQuery中将函数的输出分配给变量
- 为集合分配大量的模型弹药
- 在同一个服务工作者中处理service-worker.js有任何影响吗
- onclick函数需要双击,因为类分配延迟
- Javascript 将变量分配给警报
- 使用angular.js问题的JavaSpringREST服务
- 服务变量分配了数据,但在访问时始终未定义
- HTML服务为图像分配URL
- 意思是.js AngularJS 菜单服务为页面分配角色
- Angularjs 控制器在服务方法返回之前从服务中分配变量
- Angular 服务:将响应分配给对象是不是一种不好的做法,还是应该只使用 solve
- AngularJS:如何将服务方法分配给控制器$scope和ng-repeat(it)
- 将服务分配给控制器'的范围