2016-09-19 47 views
1

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

+0

服务在Angular中只实例化一次。如果你需要你的服务来服务多个客户端(即你的两个聊天组件),你需要调整你的服务。 – jjmontes

+0

你有什么建议@jjmontes? –

+1

这是Angular中面向对象的一个​​很好的用例。每个你的'服务'哈希调用都可以返回一个新的JS对象,该对象将专用于该特定的客户端。在AJS中,'服务'仅仅是'工厂'之上的'语法糖',服务总是如前所述的单身。以下是如何在AJS中创建对象工厂的示例: http://blog.revolunet.com/blog/2014/02/14/angularjs-services-inheritance/ – MoMo

回答

1

由于@jjmontes的评论指出,服务独身角。因此,除非该州适用于所有消费者,否则他们不应该维持任何状态。例如,适用于所有消费者的一组通用数据可以被检索一次,然后由所有人使用,而不是再次进行潜在的昂贵通话。但是,任何控制器特定的数据都应该在控制器中维护并按需传递给服务。

特别是在你的情况下,你应该把它作为参数传递给控制器​​实例调用的服务方法,而不是在服务上设置哈希值。

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

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

    return testService; 
}) 
+0

对我来说使用类并为每个控制器创建一个新实例? –

+1

@GuilhermeReda我不认为这是必然的“错误”。取决于你想如何使用它。听起来像你基本上想要一个视图模型。这是一个有很多用途的真实的东西。 – GalacticCowboy

相关问题