我有一個聊天組件,其中包含該聊天的哈希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>
服務在Angular中只實例化一次。如果你需要你的服務來服務多個客戶端(即你的兩個聊天組件),你需要調整你的服務。 – jjmontes
你有什麼建議@jjmontes? –
這是Angular中面向對象的一個很好的用例。每個你的'服務'哈希調用都可以返回一個新的JS對象,該對象將專用於該特定的客戶端。在AJS中,'服務'僅僅是'工廠'之上的'語法糖',服務總是如前所述的單身。以下是如何在AJS中創建對象工廠的示例: http://blog.revolunet.com/blog/2014/02/14/angularjs-services-inheritance/ – MoMo