Sampath
Sampath

Reputation: 65860

Run subscription only once

I need to run userProfiles$.subscribe(async res => { only once. But it works infinitely. Can you tell me how to avoid it?

This is the 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);
    }
  }

I have tried to convert it to promise like below. But no difference. Maybe I did it wrong?

 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();

Versions:

 "typescript": "2.4.2"
 "rxjs": "5.5.2",

Upvotes: 5

Views: 8888

Answers (2)

Patryk Brejdak
Patryk Brejdak

Reputation: 1601

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
});

Firstly you convert it to promise then listen to it via .then() method and wait for resolved promise.

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()
          });
        }
      });

Notice for toPromise way don't forget to import toPromise from rxjs operators and for take you should also import take method from rxjs

Update. Angular version >= 6

Since angular 6 it is required to have rxjs >= 6. In which now operators like take are now importable and used in .pipe() method. You can read more here

// somewhere at the top of file
import { take } from 'rxjs/operators';

userProfiles$.pipe(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()
          });
        }
      });

Upvotes: 5

Sampath
Sampath

Reputation: 65860

I have found a solution here using both mix of Angularfire2 and firebase native API.

I got this solution from 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);
        }
      }

Upvotes: -2

Related Questions