【发布时间】: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,同时将数据库中的任何新更改同步到列表中?
- 还是我真的做对了?
相册组件
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