简体   繁体   中英

Angular service overrides itself when called more than once

I have a chat component that have a hash id of that chat. All my api call's (done by the service) have a hash value. When I call my chat component twice, the service hash value of the first chat gets overwritten by the seconds chat.

 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>

As @jjmontes noted in a comment, services are singletons in Angular. As such, they should not maintain any state unless that state applies to all consumers. For example, a common set of data that applies to all consumers can be retrieved once and then used by all rather than making a potentially expensive call again. However, any controller-specific data should be maintained in the controller and passed to the service on demand.

Specifically in your case, instead of setting the hash value on the service, you should pass it as a parameter to the service method that the controller instances call.

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

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

  return testService;
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM