如何定期从Firebase实时数据库中获取数据。或获取数据并显示为实时数据

时间:2019-08-15 19:17:42

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

我是编程的新手,我开始使用Ionic Framework来构建应用程序作为经验。我目前正在学习构建一个基本的社交媒体应用,匿名用户可以在该应用上发布该平台。

我现在处于用户可以对帖子发表评论的阶段。但是,我很难在视图上显示每个帖子的实时评论数。

我计算评论的方式是从firebase中获取帖子数据,计算评论数,然后显示给视图。

我尝试使用间隔来获取每x秒数的帖子数据以刷新帖子数据。可以,但是问题是每次刷新/重新加载数据时,离子含量(视图)都在不断重新加载,就像屏幕不断闪烁一样。并且在使用谷歌浏览器开发工具运行一段时间后,它崩溃并显示“资源不足”

是否有更好的方法可以显示Firebase实时数据库中的实时数据?一个例子将不胜感激。

home.page.ts

import { PostsService } from '../posts/posts.service';
import { Posts } from '../posts/posts.model';


export class HomePage implements OnInit, OnDestroy {

  listedLoadedPosts: Posts[];
  private postSub: Subscription;
  commentCount: string[] = [];
  subscription: Subscription;

  constructor(
    private postService: PostsService,
  ) {}

  ngOnInit() {
    this.postSub = this.postService.posts.subscribe(posts => {
      this.listedLoadedPosts = posts; 

      const source = interval(10000);
      this.subscription = source.subscribe(val => 
      this.constantlyFetchCommentCount());
    });

  }


constantlyFetchCommentCount(){
  this.commentCount = [];
  this.postService.fetchPosts().subscribe(() => {

    // used to count comments in each posts and pushes it to commentCount[]. 
    for (const item of this.listedLoadedPosts) {
      this.commentCount.push((Object.values(item.comments).length - 1).toString());
    }

  });

}

  ionViewWillEnter() {
    this.commentCount = [];
    this.isLoading = true;
    this.postService.fetchPosts().subscribe(() => {

      // used to count comments in each posts and pushes it to commentCount[].
      for(const item of this.listedLoadedPosts){
        this.commentCount.push((Object.values(item.comments).length - 1).toString());
        this.isLoading = false;
      }
    });

  }

}

查看/ html

// placed inside ion-virtual-scroll and ion-list
<ion-label >{{commentCount[i]}}</ion-label> 

posts.service.ts

interface PostsData {
 comments: object;
 // also other data;
}

interface Comments {
  comment: string;
}


export class PostsService {
  private Pposts = new BehaviorSubject<Posts[]>([]);
  private Ccomments = new BehaviorSubject<Comment[]>([]);

  get posts() {
    return this.Pposts.asObservable();
  }

  get comments() {
    return this.Ccomments.asObservable();
  }


 constructor(private http: HttpClient) {} 



  fetchPosts() {
    return this.http
      .get<{ [key: string]: PostsData }>(
        'https://whatever.firebaseio.com/whatever.json'
      )
      .pipe(
        map(resData => {
          const posts = [];
          for (const key in resData) {
            if (resData.hasOwnProperty(key)) {
              posts.push(
                new Posts(
                  key,
                  resData[key].message,
                  // resData[key].description,
                  // etc....
                  // etc..
                   resData[key].comments
                )
              );
            }

          }
          return posts.reverse(); 
        }),
        tap(posts => {
          this.Pposts.next(posts);
        })
      );
  }






  fetchComments(id) {
    return this.http
      .get<{ [key: string]: Comments }>(
        `https://whatever.firebaseio.com/whatever/${id}/comments.json`
      )
      .pipe(
        map(resData => {
          const comment = [];
          for (const key in resData) {
            if (resData.hasOwnProperty(key)) {
              comment.push(
                new Comment(
                  key,
                  resData[key].comment
                )
              );
            }

          }
          return comment;
        }),
        tap(comment => {
          this.Ccomments.next(comment);
        })
      );
  }


}

posts.model.ts

export class Posts {
  constructor(
    public id: string,
    public message: string,
    // etc.... 
    public comments: object
  ) {}
}


export class Comment {
  constructor(
    public id: string,
    public comment: string
  ) {}
}


1 个答案:

答案 0 :(得分:-1)

Firebase为此功能提供了一些非常酷的辅助功能。在此处查看如何进行设置:

https://firebase.google.com/docs/web/setup

这将使您可以访问以下内容:

https://firebase.google.com/docs/database/web/read-and-write

尤其是on函数允许实时数据。

您可能还想看看AngularFire,这是一个将Firebase与Angular结合使用的出色库:

https://github.com/angular/angularfire2