使用FireStore和Angular 5时,我的数据以Observables的形式提供。这意味着每次数据在数据库中发生变化时,都会导致新的读取(因此据我了解,我会收取相应的费用)。
我不希望这种“持续重载,恒定充电”功能。 我想要一次读取,将我的数据存储在数组中,然后关闭连接。
这是我目前的代码。从FireStore检索时,如何修改我的服务以将产品存储在数组中,以便对我的服务的所有后续调用都返回该数组中的数据(如缓存),而不启动对FireStore的另一次调用?
product.service.ts
products: Observable<Product[]>; // *** I want this to be an array of Product objects, not an observable
getProductsAll(): Observable<Product[]> {
return this.afs.collection( 'products', ref => ref.orderBy( 'published', 'desc' ) ).snapshotChanges()
.map( actions => {
return actions.map( a => {
const id = a.payload.doc.id;
const data = a.payload.doc.data() as Product;
return { id, ...data };
})
})
products.component.ts
items: any;
ngOnInit(): void {
this.productService.getProductsAll()
.subscribe( products => {
this.items = products;
})
}
对于上下文,我的小测试应用程序导致读取次数过多,并且在数据库中只有100个文档,达到FireStore的50,000读取/天配额。
答案 0 :(得分:1)
我没有测试过这个。但是你可以在订阅之前调用.take(1)
。
<强> products.component.ts 强>
items: any;
ngOnInit(): void {
this.productService.getProductsAll()
.take(1).subscribe( products => {
this.items = products;
})
}
答案 1 :(得分:1)
以下是我提出的建议! 它具有额外的优势,在第一次从FireStore读取数据后,页面然后使用&#34;缓存&#34;更快地加载 。数据
然而,我真的很感激如果有人可以解释这是一个好的解决方案,还是有更好的解决方案?
基本上,我将Observable转换为Promise,使用take(1),并使用if语句来避免再次访问FireStore。
<强>服务强>
productsP: Promise<Product[]>;
getProductsAll(): Promise<Product[]> {
// get from cache if possible
if( !this.productsP ) {
console.log("Getting all products from FireStore...");
this.productsP = this.afs.collection( 'products', ref => ref.orderBy( 'published', 'desc' )).snapshotChanges()
.map( actions => {
return actions.map( a => {
const id = a.payload.doc.id;
const data = a.payload.doc.data() as Product;
return { id, ...data };
})
}).take(1).toPromise();
}
else {
console.log("Getting all products from cache...");
}
return this.productsP;
}
组件:更改&#39;订阅&#39;到那时&#39;。