javascript - Angular Firestore : Check if data exist and update a global variable based on that

标签 javascript angular typescript function google-cloud-firestore

要求的行为:
我想创建一个 AngularService,它检查某个文档是否存在并根据结果更新全局变量。

当前状态
该函数成功检查文档是否存在。它还会更新 if/else 语句中的全局变量。

问题
甚至,第一部分运行良好,它总是返回“未定义”。

我该如何解决?与功能范围有关吗?

我的服务:

export class ProfileFollowService {

  //global variable which should be updated
  followState: boolean;
  
  constructor(private angularFirestore: AngularFirestore) { }

  checksFollow(followingID: string, followerID: string): boolean {
    const followDoc =
    this.angularFirestore.collection(`users/${followingID}/following`).doc(followerID).ref;

    followDoc.get().then((doc) => {
      if (doc.exists) {
          this.followState = true;
      } else {
          this.followState = false;
      }
    });
    return this.followState;
  }

}

最佳答案

followDoc.get() 是返回 promise 的异步函数。为了返回更新的 this.followState 你必须等待 then

一种方法是使用 async/await

async checksFollow(followingID: string, followerID: string): boolean {
    const followDoc =
    this.angularFirestore.collection(`users/${followingID}/following`).doc(followerID).ref;

    return followDoc.get().then((doc) => {
      if (doc.exists) {
          this.followState = true;
      } else {
          this.followState = false;
      }

      return this.followState;
    }); 
  }

在您调用 checksFollow 的代码的其他部分您可以输入关键字 await并等待响应。

async someMethodToCallChecksFollow() {
    const result = await this.checksFollow();
    console.log(result);
}

如果你想在你的 html 中使用响应,我建议将 followState 从原始 boolean 更改为至 BehaviorSubject<boolean>然后调用this.followState.next(true)

例如:

export class YourService {
  public followState = new BehaviorSubject<boolean>(false);

  async checksFollow(followingID: string, followerID: string): boolean {
    const followDoc =
    this.angularFirestore.collection(`users/${followingID}/following`).doc(followerID).ref;

    return followDoc.get().then((doc) => {
      if (doc.exists) {
          this.followState.next(true);
      } else {
          this.followState.next(false);
      }

      return this.followState.getValue();
    }); 
  }
}

然后在您的 html 中您可以使用 async管道。

<div *ngIf="yourServiceInstance.followState | async">It is true</div>

关于javascript - Angular Firestore : Check if data exist and update a global variable based on that,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55007304/

相关文章:

Angular 异步管道未触发 NgOnChange 的更改检测

javascript - HTMLDocument 函数是什么?

javascript - 防止网站图像上的 HoverZoom 功能

javascript - 使用 javascript UDF 对 BigQuery 中整数数组的值求和

javascript - Javascript/Angular2 中的安全字符串

javascript - Angular 渲染在组件中动态附加 &lt;script&gt;-标签

javascript - 如何使用 Webpack 运行 Angular 2 AOT

javascript - 如何从 create-react-app 迁移到 typescript?

javascript - 将上传文件转换为字节数组以发送到 Angular/Typescript 中的 API 请求

typescript - 如何使用angular2中的链接参数数组从子组件导航到上层路由?