2016-09-19 33 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

相關問題