仅运行一次订阅

时间:2017-12-08 17:00:06

标签: angular typescript rxjs observable google-cloud-firestore

我只需要运行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",

2 个答案:

答案 0 :(得分:2)

承诺方式:

transition

首先,您将其转换为承诺,然后通过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 }); 方法收听并等待已解决的承诺。

可观察的.take(1)

.then()

请注意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() }); } }); 方式忘记从rxjs运算符导入toPromise,而对于toPromise,您还应该从rxjs导入take方法

答案 1 :(得分:-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);
        }
      }