tobias hassebrock
tobias hassebrock

Reputation: 357

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

Requested behaviour:
I would like to create an AngularService which checks if a certain document exists and updates a global variable based on the result.

Current State
The function checks the existence of the document successfully. It also updates the global variable in the if/else statement.

issue
Even, the first part works well, it always returns "undefined".

How can I fix that? Is it related to function scope?

My Service:

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

}

Upvotes: 2

Views: 1135

Answers (1)

Arif
Arif

Reputation: 1645

followDoc.get() is async function that returns promise. In order to return updated this.followState you have to wait for then

one way to do this is to use 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;
    }); 
  }

In other part of your code where you call checksFollow you can put keyword await and wait for the response.

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

If you want to use the response in your html, I would suggest changing followState from primitive boolean to BehaviorSubject<boolean> and then call this.followState.next(true)

For example:

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

And then in your html you can use async pipe.

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

Upvotes: 1

Related Questions