Передача данных в службу с контроллера ПОСЛЕ получения информации с сервера

#angularjs #ionic-framework #angularjs-scope #angularjs-service #angularjs-controller

#angularjs #ionic-framework #angularjs-область #angularjs-сервис #angularjs-контроллер

Вопрос:

Мне нужно передать данные в массив в службе после получения с сервера. 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.
Бонус: я не исследовал, чтобы функция get в контроллерах постоянно опрашивала входящие сообщения, однако, если вы можете сказать мне, что это будет полезно и сэкономит время.

Комментарии:

1. Вы хотите отправить данные $scope.messgaepool в ChatService? Это ваше требование?

2. Да, это то, что я хочу.

Ответ №1:

контроллер

 .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];
        }
      }
     }
    }
 });
  

Надеюсь, это вам поможет 🙂 Спасибо