1

Я работаю на интеграции чата в моем приложении Ионного с Firebase и я стараюсь, чтобы отобразить сообщение, что:

  1. отправляется
  2. являются от предыдущее время

До сих пор у меня нет проблем с получением предыдущих сообщений, которые они отображают красиво, или у меня нет проблем с отправкой новых сообщений.

ОДНАКО Я не могу понять способ сделать ОБА функции одновременно.

Если я использую следующие коды, у меня есть эта ошибка:

TypeError: $scope.messages.push is not a function 

Любая идея?

Вот код, у меня есть, как мой контроллер:

.controller('Messages',['$scope', '$ionicScrollDelegate', '$timeout', '$firebaseArray', 'CONFIG', '$document', '$state', function($scope, $ionicScrollDelegate, $timeout, $firebaseArray, CONFIG, $document, $state) { 
    $scope.hideTime = false; 
    var myId = firebase.auth().currentUser.uid; 
    var otherId = "0LhBcBkECAXn6v12lA2rlPIsQNs2"; 
    var discussion = myId + otherId; 

    var isIOS = ionic.Platform.isWebView() && ionic.Platform.isIOS(); 

    //Recieve messages 
    var ref = firebase.database().ref('/messages/' + discussion); 
    ref.orderByChild("timestamp").on("value", function(snapshot1) { 
    console.log(snapshot1.val() + "HEY"); 
    $scope.messages = snapshot1.val(); 

    }) 

    //Send messages 
    $timeout(function(){ 
    $scope.sendMessage = function() { 

     var d = new Date(); 
     var g = new Date(); 
     d = d.toLocaleTimeString().replace(/:\d+ /, ' '); 
     g = g.toLocaleTimeString().replace(/:\d+ /, ' ') + new Date(); 



     $scope.messages.push({ 
     userId: myId, 
     text: $scope.data.message, 
     time: d 
     }); 

     $scope.sendMessages = firebase.database().ref('/messages/' + discussion).push({ 
     userId: myId, 
     text: $scope.data.message, 
     time: d, 
     timestamp: g 
     }); 

     console.log($scope.messages); 

     delete $scope.data.message; 
     $ionicScrollDelegate.scrollBottom(true); 

    }; 

    $scope.inputUp = function() { 
     if (isIOS) $scope.data.keyboardHeight = 216; 
     $timeout(function() { 
     $ionicScrollDelegate.scrollBottom(true); 
     }, 300); 

    }; 

    $scope.inputDown = function() { 
     if (isIOS) $scope.data.keyboardHeight = 0; 
     $ionicScrollDelegate.resize(); 
    }; 

    $scope.closeKeyboard = function() { 
     // cordova.plugins.Keyboard.close(); 
    }; 
    $scope.data = {}; 
    $scope.myId = myId; 
    $scope.messages = []; 



    }) 

}]); 

А вот код для моего HTML:

<ion-view view-title="Chat Detail"> 
<ion-content class="padding" start-y="430"> 
    <!-- *messages/content messages --> 
    <ol class="messages"> 
     <!-- *self/container self messages --> 
     <li ng-repeat="message in messages" ng-class="{other: message.userId != myId}" class="self"> 
      <!-- *avatar/avatar image --> 
      <div class="avatar"> 
       <img src="img/82.jpg"> 
      </div> 
      <!-- *msg/messages --> 
      <div class="msg"> 
       <p>{{ message.text }}</p> 
       <time> 
        <i class="icon ion-ios-clock-outline"></i> 
        {{message.time}} 
       </time> 
      </div> 
     </li> 
    </ol> 
</ion-content> 
<!-- *bar-detail/color bar and input --> 
<ion-footer-bar keyboard-attach class="item-input-inset bar-detail"> 
    <label class="item-input-wrapper"> 
    <input type="text" placeholder="Type your message" on-return="sendMessage(); closeKeyboard()" ng-model="data.message" on-focus="inputUp()" on-blur="inputDown()" /> 
    </label> 
    <a class="button button-icon icon ion-arrow-return-left" ng-click="sendMessage()" ></a> 
</ion-footer-bar> 

Спасибо за ваши советы и комментарии заранее!

ответ

0

Решение найдено после 19h, так смешно:

я должен был избавиться от этой части кода.

$scope.messages.push({ 
     userId: myId, 
     text: $scope.data.message, 
     time: d 
     }); 

и убедитесь, что значение для получения сообщений был на «на» вместо «один раз», чтобы действовать с базой данных в реальном времени Firebase.

Смежные вопросы