gpt4 book ai didi

javascript - 当多次调用时,Angular 服务会覆盖自身

转载 作者:行者123 更新时间:2023-11-27 22:31:01 24 4
gpt4 key购买 nike

我有一个聊天组件,其中包含该聊天的哈希 ID。我的所有 api 调用(由服务完成)都有一个哈希值。当我调用聊天组件两次时,第一次聊天的服务哈希值会被第二次聊天覆盖。

angular.module('testModule', [])
.controller('testController', function(testService, $scope) {
var vm = this;

vm.init = function() {
vm.hash = vm.hash();
testService.setHash(vm.hash);
}

vm.getServiceHash = function() {
vm.serviceHash = testService.hash;
}

vm.init();
})
.service('testService', function() {
var testService = {
hash: null
};

testService.setHash = function(hash) {
testService.hash = hash;
}

return testService;
})
.directive('test', function() {
return {
restrict: 'E',
template: $("#test\\.html").html(),
controller: 'testController',
controllerAs: 'test',
bindToController: {
hash: '&',
},
scope: {}
}
});

var app = angular.module('myApp', ['testModule']);
app.controller('myController', function($scope) {})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>

<body>
<div ng-app="myApp" ng-controller="myController">
<test hash="'123'"></test>
<test hash="'321'"></test>
</div>

<script type="text/ng-template" id="test.html">
<p>
<h2> Controller hash: {{test.hash}} </h2>
<button type="button" ng-click="test.getServiceHash()">Get service hash</button>
<h2> Service hash: {{test.serviceHash }} </h2>
</p>
</script>

</body>

最佳答案

正如 @jjmontes 在评论中指出的那样,服务在 Angular 中是单例。因此,他们不应该维持任何状态,除非该状态适用于所有消费者。例如,适用于所有消费者的一组通用数据可以被检索一次,然后被所有人使用,而不是再次进行可能昂贵的调用。但是,任何特定于 Controller 的数据都应在 Controller 中维护并根据需要传递给服务。

具体来说,在您的情况下,您应该将其作为参数传递给 Controller ​​实例调用的服务方法,而不是在服务上设置哈希值。

.service('testService', function() {
var testService = {
};

testService.callService = function(hash) {
// call an API or whatever, passing the hash
}

return testService;
})

关于javascript - 当多次调用时,Angular 服务会覆盖自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39579755/

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