【问题标题】:(Ionic - Firebase) Why only the last data is diplayed?(Ionic - Firebase) 为什么只显示最后的数据?
【发布时间】:2017-09-23 19:04:58
【问题描述】:

问题

我正在使用 Ionic 和 Firebase 来开发应用程序。

不知道为什么,只显示最后添加到数据库的数据。

我尝试使用“value”而不是“child_added”,但我得到了一个列表,其中只有原始值 {"data":"Hello"}

我想得到一个只有值的列表!

感谢您的帮助

news.html

<ion-view title="News">
 <ion-nav-buttons side="right">
  <button ng-click="messageCreator()" class="button button-icon ion-ios-chatboxes-outline"></button>
 </ion-nav-buttons>

 <ion-content class="has-header">
  <ion-list ng-controller="displayMessages">
   <ion-item ng-click="goCalendar()" ng-repeat="val in value"  class="item item-icon-right">
    {{val}}
     <a class="icon icon-accessory ion-chevron-right"></a>
   </ion-item>
  </ion-list>
 </ion-content>
</ion-view>

新建数据的方法

$scope.messageCreator = function () {
  $ionicPopup.prompt({
    title: 'New message',
  }).then(function(res) {
      firebase.database().ref('ParentName').push().set({
        data: res
      }).then(function() {
         alert("Data submitted");
      }).catch(function(error) {
        alert(error.message);
     });
  });
}

显示数据的方法

$scope.displayMessages = function ($timeout) {
  var testRef = firebase.database().ref('ParentName');

  testRef.on('child_added', function (snapshot) {
    $timeout(function () {
      update(snapshot);  
    });
  });

  function update (snapshot) {
    $scope.value = snapshot.val();
  }
}

仅显示最后添加到数据库的数据

【问题讨论】:

  • 到列表...

标签: javascript firebase ionic-framework firebase-realtime-database


【解决方案1】:

我认为没有任何理由:

testRef.on('child_added', function (snapshot) {
  $timeout(function () {
    update(snapshot);  
  });
});

问题在于数据的类型。你应该将你的数据声明为一个 Observable,这样刷新是即时的,不需要额外的代码。声明是这样的:

data: FirebaseListObservable<any[]>;

这种类型可以包含在:

import {AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database';

您可以查看准备好的教程here,它还提供了一个现场示例来测试它。

【讨论】:

  • 这是在 TypeScript 中,不是...?请问如何在Javascript中做同样的事情?
  • 是的,这是打字稿。为什么你需要 Javascript,如果你使用 Ionic 打字稿是默认的。 Javascript(ES6)中的导入相同。您可以在 Js 中声明数据,如: var data = FirebaseListObservable[]; .我不确定这是否可行。但首先你应该使用 Ionic 推荐的打字稿
  • 其实多亏有你,我开始学习 TypeScript 并重新开始我的项目...会更好^^
  • 我认为 Typescript 真的很简单。当我开始使用 Ionic 时,我学会了 Ts。祝你好运!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-18
  • 2020-02-04
  • 2013-03-30
  • 2019-09-15
  • 1970-01-01
  • 1970-01-01
  • 2019-09-09
相关资源
最近更新 更多