gpt4 book ai didi

Angular Firestore subscribe() 触发两次

转载 作者:行者123 更新时间:2023-12-01 23:24:31 25 4
gpt4 key购买 nike

每当我的 Firebase 文档数据发生变化时,我只想调用一个函数,但是将 .subscribe() 链接到我的 valueChanges() 会导致订阅每次有更新时触发两次。

没有订阅的基本代码:

home.component.ts:

constructor(private firestore: AngularFirestore) { }

ngOnInit(): void {
let docName = this.buildDocName();
this.plants = this.firestore.collection('officePlants').doc(docName).valueChanges();
}

home.component.html:

<mat-list *ngIf="(plants | async)">
<mat-list-item>Humidity: {{ (plants | async)?.humidity }}</mat-list-item>
<mat-list-item>Temperature: {{ (plants | async)?.temperature }}</mat-list-item>
</mat-list>

此代码导致订阅触发两次:

home.component.ts:

ngOnInit(): void {
let docName = this.buildDocName();
this.plants = this.firestore.collection('officePlants').doc(docName).valueChanges()
.subscribe(data => {
if (!data)
return;

console.log('doc updated...', data);
// ...
});
}

最佳答案

它实际上可能会更改两次,而您的订阅正在按预期进行。你只是不处理那个案子。如果没有变化,请尝试对其进行去抖动或过滤。

this.plants = this.firestore.collection('officePlants').doc(docName).valueChanges()
.pipe(
debounceTime(500)
//distinctUntilChanged() // or try this, ignores equal data
)
.subscribe(data => { /*...*/});

第二个问题可能是您忘记了退订 并且您同时拥有两个实时订阅。您需要正确地摆脱它们。

ngOnDestory() {
this.plants.unsubscribe();
}

关于Angular Firestore subscribe() 触发两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67514628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com