0

我需要從服務器獲取數據後傳遞到服務中的數組。所述controller運行函數來檢索數據,如圖從控制器傳遞數據到服務器後從服務器接收信息

.controller("messagesController", function($scope, $stateParams, RegisterP) { 
    // function here retrives data from the RegisterP parameter above calling another service 
    $scope.messagepool = [ 1, 2]; //I add the data I get here to an array 
}) 

此數組然後被髮送到一個服務

.service('ChatService', function() { 
return { 
    chats: [ 
    { 
     id: "1", 
     message: "Chat Message 1" 
    } 
    ], 
    getChats: function() { 
    return this.chats; 
    }, 
    getChat: function(chatId) { 
    for(i=0;i<this.chats.length;i++){ 
     if(this.chats[i].id == chatId){ 
     return this.chats[i]; 
     } 
    } 
    } 
} 
}) 

這進而將發送到一個視圖/視圖。我需要知道如何發送來自控制器的信息,使其佔用chats: [],因此視圖在實時更新。使用Ionic框架。 獎勵:我還沒有研究過控制器中的獲取函數是否持續查詢傳入的消息,但是如果您可以告訴我它會有所幫助並節省時間。

+0

你想$ scope.messgaepool數據發送到ChatService?這是你的要求嗎? –

+0

是的,這就是我想要的。 – Olli

回答

0

控制器

.controller("messagesController", function($scope, $stateParams, RegisterP,ChatService) { 
// function here retrives data from the RegisterP parameter above calling another service 
    $scope.messagepool = [ 1, 2]; //I add the data I get here to an array 
    ChatService.sendData($scope.messagepool); 
}); 

服務

.service('ChatService', function() { 
    return { 
    sendData:function(data){ 
     this.chatData=data; 
     console.log(this.chatData); 
     // this.getChats(); you can call service function from here 
     }, 
    getChats: function() { 
     console.log(this.chatData); // it will work here too 
     return this.chats; 
     }, 
    getChat: function(chatId) { 
     for(i=0;i<this.chats.length;i++){ 
     if(this.chats[i].id == chatId){ 
     return this.chats[i]; 
     } 
     } 
    } 
    } 
}); 

希望它會幫助你:)謝謝

相關問題