gpt4 book ai didi

AngularJS 在其他函数之前运行服务函数

转载 作者:行者123 更新时间:2023-12-04 07:01:36 24 4
gpt4 key购买 nike

我是 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();
}]);

我有一个使用此服务配置的 Controller
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;
}]);

这里的问题是 myService.user.something 可能未定义,因为调用此代码时 AJAX 请求可能尚未完成。有没有办法在运行任何其他代码之前完成服务?我希望服务功能“loadConfiguration”只运行一次,而不管依赖它的 Controller 数量如何。

最佳答案

如果要确保在 AJAX 调用返回后执行 Controller 中的代码,则可以使用事件。

在您的服务中使用它:

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();
}]);

在您的 Controller 中:
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;
})
}]);

您甚至可以将对象附加到事件。

请引用 https://docs.angularjs.org/api/ng/type/ $rootScope.Scope 。

关于AngularJS 在其他函数之前运行服务函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23786963/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com