如何根据从其他服务获取 UID 在服务中设置 Firestore 引用异步?

How to set a firestore reference async in service depening on getting UID from other service?

基本上我想做这个

项目服务:

  privateFolderRef = this.db.collection('users').doc('private').collection(this.userService.uniqueId);
  publicFolderRef = this.db.collection('users').doc('public').collection(this.userService.uniqueId;
//later in service
this.getProjects() { this.privateFolderRef.doc('name')};//not async

用户服务:

  get uniqueId() {
    return this.afAuth.auth.currentUser.uid;
  }

问题是 currentUser 是异步的,并不总是准备好。所以基本上我如何确保我的 getter 函数总是 returns 一个 uid,我该怎么做才能确保使用该 ref 的方法等待以干净的方式设置 refs?

我知道这个:

在组件中等待会给我留下很多重复。真的不想那样做。有人找到了在服务中更清洁的解决方案吗?

已解决 没有办法从另一个服务中获取一致的UID,所以我就这样解决了。在服务本身中进行。

  privateFolderRef;
  publicFolderRef

  constructor(
    private db: AngularFirestore,
    public afAuth: AngularFireAuth
  ) {
    this.afAuth.authState.subscribe(user => {
      this.privateFolderRef = this.db.collection('users').doc('private').collection(user.uid);
      this.publicFolderRef = this.db.collection('users').doc('public').collection(user.uid);
    })
  }

更新 并非在所有情况下都有效,重新加载构造函数是在 class 中的正常方法调用之后执行的。 Returns 未定义会使应用程序崩溃。

更新 2 我确定 auth 在某个时刻不为 null 的唯一方法是在组件本身中等待。这让我可以最大程度地控制用户真正返回的时间。我真正想要的是一个等待用户(服务)的中心点,如果准备就绪,则加载一个组件。现在的做法会导致大量重复,因为组件彼此独立工作。

您应该等待 afAuth 在您需要的地方初始化 uniqueID。 例如在 ProjectService 中你得到:

// wait here for afAuth to be ready, you have to inject it.
privateFolderRef = this.db.collection('users').doc('private').collection(this.userService.uniqueId);
publicFolderRef = this.db.collection('users').doc('public').collection(this.userService.uniqueId);

根据 afAuth 的实现,如果可能的话,您可能 subscribe 这样做,可能会有一个选择。

编辑:

如果您可以访问 afAuth 服务并且您无法检测它何时初始化,您可以创建一个接收数据的 Observable。 检查 https://rxjs-dev.firebaseapp.com/guide/subject