从服务器接收信息后,从控制器将数据传递给服务

时间:2016-09-30 15:41:38

标签: angularjs ionic-framework angularjs-scope angularjs-service angularjs-controller

从服务器获取后,我需要将数据传递给服务中的数组。 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 Framework。 Bonus:我还没有研究过让控制器中的get函数不断轮询传入的消息,但是如果你能告诉我它会有所帮助并节省时间。

1 个答案:

答案 0 :(得分: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];
        }
      }
     }
    }
 });

希望它能帮到你:)谢谢

相关问题