gpt4 book ai didi

javascript - AngularjS 服务/工厂在启动时加载但未使用

转载 作者:行者123 更新时间:2023-11-30 12:57:36 25 4
gpt4 key购买 nike

我的 AngularJS 应用程序有问题。我定义了一些工厂,这些工厂被注入(inject)到一些 Controller 中(在需要的地方)。我的问题是这些工厂在我第一次启动应用程序时被初始化。

导致问题的服务之一:

PlanningPoker.factory('PokerTable', function ($http) {
var baseURL = "/api/pokertable/";

return {
list: function list(playerId) {
return $http.get(baseURL, {params: {playerid : playerId}});
},
save: function save(pokertable) {
return $http.post(baseURL, pokertable, {});
}
};

});

这个服务在 Controller 中是这样使用的:

PlanningPoker.controller('PokerTableListController', function ($rootScope, $scope, $route, PokerTable, SocketEvent) {
PokerTable.list($rootScope.playerId).
success(function (data, status, headers, config) {
$scope.pokertables = data;
});

});

此外,当我从 Controller 回调中删除 PokerTable 服务时,该服务会被调用。我通过在服务中添加一个 console.log 来尝试此操作,无论该服务是否在任何 Controller 中使用,它都会被调用。

对此有什么想法吗?我认为服务只有在需要时才会延迟加载?

问候马克

最佳答案

服务在被注入(inject)器注入(inject)时被构造或检索,以确保依赖关系正常工作。你可以阅读它here

或者,您可以根据需要使用 $injector 服务来获取服务。这是一个例子:

    .controller('test', function($scope, $injector) {
$scope.func = function() {
var factory = $injector.get('factory');
};
});

http://jsfiddle.net/NaYmd/

您会注意到在您单击 span 之前不会调用服务中的警报,因为那是注入(inject)器导致工厂构建的时候。

关于javascript - AngularjS 服务/工厂在启动时加载但未使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18504863/

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