【问题标题】:AngularFire and Firestore - Querying collection once whilst navigating componentsAngularFire 和 Firestore - 在导航组件时查询一次集合
【发布时间】:2020-02-14 08:51:29
【问题描述】:

我正在尝试减少对我的 firestore 数据库执行的读取。在一个小演示中,我有两个组件。

组件 1

组件 1 是存储在 firestore 集合 company/artists 中的艺术家列表

组件 2

组件 2 是存储在 firestore 集合 company/albums 中的任何艺术家的专辑列表

我通过在每个专辑文档中列出artist_id 将艺术家连接到专辑。

我有一个在组件中引用的服务。该服务包含我在服务构造函数中启动的 angularfire 集合查询。我在查询函数中放置了一个控制台日志,以记录调用该函数的时间。我基本上希望专辑查询只发生一次,即使当我导航回艺术家组件并返回时,我也不希望它再次触发。如果我将新项目添加到列表中,我希望它能够同步,它确实如此。

但是,现在即使 console.log('get all items called'); 在我浏览组件时只被触发一次,console.log('data = ', data) 每次我进入相册组件时都会被触发,这让我觉得我确实在查询数据库每次。

问题

  1. 如何确保此查询只运行一次?
  2. 如何实现问题 1,同时将数据库中的任何新更改同步到列表中?
  3. 还是我真的做对了?

相册组件

import { Component, OnInit } from '@angular/core';
import { AlbumItemsService } from '../services/category-items.service';

@Component({
   selector: 'app-album-items',
   templateUrl: './album-items.component.html',
   styleUrls: ['./album-items.component.css']
 })

export class AlbumItemsComponent implements OnInit {
  constructor(public albumItemsService: AlbumItemsService) { }
  ngOnInit(): void {}
}

服务

import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class AlbumItemsService {

   private itemsCollection: AngularFirestoreCollection<any>;
   items: Observable<any[]>;

   constructor(private afs: AngularFirestore) { 
     console.log('Album Item Service Called')
     this.getAllItems();
   }

   getAllItems(){
      console.log('get all items called');
      this.itemsCollection = this.afs.collection<any>('url');
      this.items = this.itemsCollection.snapshotChanges().pipe(
         map(actions => actions.map(a => {
         const data = a.payload.doc.data();
         const id = a.payload.doc.id;
         console.log('data = ', data)
         return { id, ...data };
      }))
  );
 }
}

HTML

<ul>
  <li *ngFor="let item of AlbumItemsService.items | async">
    {{ item.item_title }}
  </li>
</ul>

更新

我弄乱了本机 Firestore 代码而不是 angularfire。

this.db.collection("collection").onSnapshot((querySnapshot) => {
    var cities = [];
    querySnapshot.forEach((doc) => {
        cities.push(doc.data());
    });
    console.log("cities = ", cities);
});

似乎好像它不会每次都查询数据库。谁能确认一下?

【问题讨论】:

    标签: angular google-cloud-firestore


    【解决方案1】:

    我主要看你的“更新”。如果你想查询集合,你应该使用.get 而不是.onSnapshot 可以找到参考here

    【讨论】:

    • 谢谢@vitooh。两者有什么区别?我基本上想在服务中对集合运行一次查询,因为它会在导航时被许多组件使用。我只是不希望它多次触发。
    • .onSnapshot 为 QuerySnapshot 事件附加一个侦听器,而 get 执行查询并将结果作为 QuerySnapshot 返回。所以如果你需要做一次快照似乎更合理。
    猜你喜欢
    • 2019-07-20
    • 2018-06-19
    • 2019-05-12
    • 2018-10-16
    • 2020-09-21
    • 2021-06-29
    • 1970-01-01
    • 2019-10-02
    • 2019-07-25
    相关资源
    最近更新 更多