Ionic 为什么在firestore中我读取操作和使用统计数据显示为双倍?

gzjq41n4  于 2022-12-08  发布在  Ionic
关注(0)|答案(1)|浏览(139)

this is starting with the implementation and use of Google's cloud firestore in an ionic project,
Ionic:
Ionic CLI : 6.19.0 (C:\Users\Windows 10\AppData\Roaming\npm\node_modules@ionic\cli) Ionic Framework
: @ionic/angular 6.1.9 @angular-devkit/build-angular : 14.0.1
@angular-devkit/schematics : 14.0.1 @angular/cli
: 14.0.1 @ionic/angular-toolkit : 6.1.0
Capacitor:
Capacitor CLI : 3.5.1 @capacitor/android : 3.5.1
@capacitor/core : 3.5.1 @capacitor/ios : not installed
Utility:
cordova-res : 0.15.4 native-run : 1.6.0
System:
NodeJS : v16.14.2 (C:\Program Files\nodejs\node.exe) npm : 8.5.0 OS : Windows 10
I already have all the libraries installed and the connection to the project in firebase configured. I am doing a simple read query to a root collection to obtain all the documents in that collection, this consists of 400 docs and I am going to check the firestore cloud usage statistics in the firebase console and I see that 800 operations are performed of reading, I also observed that with any writing operation, twice as many operations are also recorded in the statistics, it does not matter the type of operation, but it always records double. Does anyone know the reason or why it is registering twice as many operations?

app.component.ts

import { Observable } from 'rxjs/Observable';
import { FirebaseService } from './../../services/firebase/firebase.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
  items: Observable<any[]>;

  constructor(
    private firebase: FirebaseService
  ) { }

  async ngOnInit() {

    this.items = await this.firebase.firestore.collection('items').valueChanges();
    
  }

}

app.component.html

<ion-content >
  <pre> {{items | async | json }} </pre>
</ion-content>

Usage Metrics

Note: only one query was actually made and the reading operations were recorded in 2 minutes. 11:18 and 11:19 for a total of 800 read operations.

5uzkadbs

5uzkadbs1#

This is because of the method: valueChanges()
It might change twice and your subscription is doing what it should. You're just not handling that case. Try either to denounce it or filter it if there was no change.

this.items = this.firestore.collection('items').valueChanges()
  .pipe(
    debounceTime(300);
   )
  .subscribe(data => { });

Also, you are kinda subscribing but not doing the unsubscription basically, the method reads the data and then checks if any value has been changed. So you need "close" de connection when the component destroys, to avoid double render o calling each render of the DOM.

async ngOnDestory() {
  this.items.unsubscribe();
}

相关问题