我是AngularJS的新手,并且有一个加载我的初始用户配置的服务
angular.module('myApp').service('myService', ['$http', function ($http) {
var self = this;
self.user = {};
self.loadConfiguration = function () {
$http.get('/UserConfig').then(function (result) {
self.user = result.data;
});
};
self.loadConfiguration();
}]);
Run Code Online (Sandbox Code Playgroud)
我有一个使用此服务配置的控制器
angular.module('myApp').controller('myController', ['$scope', 'myService', function ($scope, myService) {
var self = this;
// calculation based on service value
self.something = myService.user.something * something else;
}]);
Run Code Online (Sandbox Code Playgroud)
这里的问题是myService.user.something可能是未定义的,因为调用此代码时AJAX请求可能尚未完成.有没有办法在任何其他代码运行之前完成服务?我希望服务函数'loadConfiguration'只运行一次,而不管依赖它的控制器的数量.
您可以在.run()
函数内调用您的服务方法
运行块
运行块是Angular中与main方法最接近的东西.运行块是需要运行以启动应用程序的代码.在配置完所有服务并创建注入器后执行.运行块通常包含难以进行单元测试的代码,因此应在隔离模块中声明,以便在单元测试中忽略它们.
https://docs.angularjs.org/guide/module
angular.module('myApp').run(function()){
//use your service here
}
Run Code Online (Sandbox Code Playgroud)
处理ajax延迟的一种方法是使用$rootScope.$broadcast()
$ http.success上的函数,该函数将自定义事件广播到所有控制器.Antoher的方法是使用promises并在解析后在控制器中执行操作.以下是一些想法:https://groups.google.com/forum/#!topic/angular / qagzXXhS_VI/discussion
如果要确保在AJAX调用返回后控制器中的代码执行,则可以使用事件.
在您的服务中使用此:
angular.module('myApp').service('myService', ['$http', '$rootScope', function ($http, $rootScope) {
var self = this;
self.user = {};
self.loadConfiguration = function () {
$http.get('/UserConfig').then(function (result) {
self.user = result.data;
$rootScope.$broadcast('myService:getUserConfigSuccess');
});
};
self.loadConfiguration();
}]);
Run Code Online (Sandbox Code Playgroud)
在你的控制器中:
angular.module('myApp').controller('myController', ['$scope', 'myService', function ($scope, myService) {
var self = this;
$scope.$on('myService:getUserConfigSuccess', function() {
// calculation based on service value
self.something = myService.user.something * something else;
})
}]);
Run Code Online (Sandbox Code Playgroud)
您甚至可以将对象附加到事件中.
请参阅https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope.
归档时间: |
|
查看次数: |
11923 次 |
最近记录: |