我有一个聊天组件,其中包含该聊天的哈希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