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

标签 javascript angularjs angularjs-directive

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

相关文章:

javascript - angularJs - 如何获取过滤数组

javascript - 在 AngularJS 的自定义指令中包含第一个子 html

javascript - 在不同的应用程序中使用 angular.js 指令?

javascript - AngularJS:包含相同的 Controller

javascript - 为什么我的 img 中的 require() 在与 Bulma 一起使用时无法正常工作?

javascript - 如何使用 JS 获取 div 元素内的值

javascript - 使用 jquery 执行 GET 请求

mysql - 在使用 MySql、express、angular、nodejs 时,express 和 node 的端口是否不同

javascript - AngularJS:将数据从 ng-init 传递到 &lt;script&gt;

javascript - AngularJS 许多 Controller ng 设计 Material