首页 > 解决方案 > Firestore first()).toPromise() always gives old value even I have re-run with new changes

问题描述

I have this method on a service:

     getUserLink(uid: string): Promise<ConnectionLinkModel> {
            return this.afs.doc<ConnectionLinkModel>
(`userConnectionLinks/${uid}`).valueChanges().pipe(first()).toPromise();
        }

This is working fine for the first time. But let's say I have changed the Firestore data manually and re-run this method again (This is very important. I know since this is promise it'll not listen to the changes automatically. But why it doesn't give new value even though I have re-run it again.). But it never gives changed value. i.e. it always gives old value. How can I handle this use case?

    ngOnInit(): void {
        const res: ConnectionLinkModel = await 
this.connectionLinkService.getUserLink(this.authService.currentUserUid);
      }

Note: When Page loads it runs again. But it'll never give new value. Why?

标签: angularfirebaseionic-frameworkgoogle-cloud-firestoreangularfire

解决方案


如果您启用了持久性,那么您将获得的第一个数据将始终来自本地缓存。

文档

要检查您是从服务器接收数据还是从缓存接收数据,请在快照事件中使用 SnapshotMetadata 上的 fromCache 属性。如果 fromCache 为真,则数据来自缓存并且可能是陈旧的或不完整的。如果 fromCache 为 false,则数据是完整的,并且是服务器上最新更新的最新数据。

 getUserLink(uid: string): Promise<ConnectionLinkModel> {

                return this.afs.doc<ConnectionLinkModel>(`userConnectionLinks/${uid}`)
                                 .valueChanges()
                                 .pipe(debounceTime(1000)).pipe(first()).toPromise();
            }

推荐阅读