仅运行一次订阅

问题描述 投票:4回答:2

我只需要运行一次userProfiles$.subscribe(async res => {。但它无限运作。你能告诉我怎么避免吗?

这是video of that issue

.TS

async loginWithGoogle(): Promise<void> {
    try {
      const result = await this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
      const userId: string = result.additionalUserInfo.profile.id;
      const userProfile: AngularFirestoreDocument<UserProfile> = this.fireStore.doc(`userProfile/${userId}`);
      const userProfiles: AngularFirestoreCollection<UserProfile> = this.fireStore.collection('userProfile/', ref => ref.where('email', '==', result.additionalUserInfo.profile.email));
      const userProfiles$: Observable<UserProfile[]> = userProfiles.valueChanges();

      userProfiles$.subscribe(async res => { //problem is here
        if (res.length == 0) {
          await userProfile.set({
            id: userId,
            email: result.additionalUserInfo.profile.email,
            creationTime: moment().format(),
            lastSignInTime: moment().format()
          });
        } else {
          await userProfile.update({
            lastSignInTime: moment().format()
          });
        }
      });
    }
    catch (err) {
      console.log(err);
    }
  }

我试图将它转换为promise,如下所示。但没有区别。也许我做错了?

 userProfiles$.map(async res => {
        if (res.length == 0) {
          await userProfile.set({
            id: userId, email: result.additionalUserInfo.profile.email,
            creationTime: moment().format(),
            lastSignInTime: moment().format()
          });
        }
      }).toPromise();

版本:

 "typescript": "2.4.2"
 "rxjs": "5.5.2",
angular typescript rxjs observable google-cloud-firestore
2个回答
2
投票

Promise way:

userProfiles$.toPromise().then((res) => {
   if (res.length == 0) {
      await userProfile.set({
         id: userId, email: result.additionalUserInfo.profile.email,
         creationTime: moment().format(),
         lastSignInTime: moment().format()
      });
   }
}).catch(err => {
   // handle error
});

首先,您将其转换为承诺,然后通过.then()方法收听并等待已解决的承诺。

Observable .take(1)

userProfiles$.take(1).subscribe(async res => { //problem is here
        if (res.length == 0) {
          await userProfile.set({
            id: userId,
            email: result.additionalUserInfo.profile.email,
            creationTime: moment().format(),
            lastSignInTime: moment().format()
          });
        } else {
          await userProfile.update({
            lastSignInTime: moment().format()
          });
        }
      });

关于toPromise方式的注意事项不要忘记从rxjs运算符导入toPromisetake你还应该从rxjs导入take方法


-2
投票

我在这里找到了使用Angularfire2firebase native API混合的解决方案。

我从Michael here得到了这个解决方案。

Firestore native API

get
get() returns firebase.firestore.QuerySnapshot

Executes the query and returns the results as a QuerySnapshot.

Returns
non-null firebase.firestore.QuerySnapshot A promise that will be resolved with the results of the query.

.TS

 constructor() {
     this.db = firebase.firestore();
  }

   async loginWithGoogle(): Promise<string> {
        try {
          const response = await this.afAuth.auth.signInWithRedirect(new firebase.auth.GoogleAuthProvider());
          const result = await this.afAuth.auth.getRedirectResult();
          this.user = result.user;
          const userId: string = result.user.uid;
          const userProfile: AngularFirestoreDocument<UserProfile> = this.fireStore.doc(`userProfile/${userId}`);
          const res = await this.db.collection("userProfiles").where("email", "==", data).get();
          if (res.docs.length === 0) {
            await userProfile.set({
              id: userId,
              email: result.additionalUserInfo.profile.email,
              creationTime: moment().format(),
              lastSignInTime: moment().format()
            });
          } else {
            await userProfile.update({
              lastSignInTime: moment().format()
            });
          }
          return result.additionalUserInfo.profile.email;
        }
        catch (err) {
          console.log(err);
        }
      }
© www.soinside.com 2019 - 2024. All rights reserved.