Confirming the existence of data in Angular Firestore and adjusting a global variable accordingly

Desired Outcome:
I am looking to develop an AngularService that can verify the existence of a specific document and adjust a global variable based on the outcome.

Current Status
The function effectively confirms the presence of the document and updates the global variable within the if/else conditions.

Problem
However, despite the initial success, it consistently returns "undefined".

How do I rectify this issue? Could it be related to function scope?

The Code Snippet for My Service:

export class ProfileFollowService {

  //global variable to be modified
  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;
  }

}

Answer №1

followDoc.get() is an asynchronous function that returns a promise. To get the updated value of this.followState, you need to wait for the then statement.

One approach to achieve this is by using 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;
    }); 
  }

When calling checksFollow in another part of your code, you can use the keyword await to wait for the response.

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

If you intend to use the response in your HTML, I recommend changing followState from a primitive boolean to BehaviorSubject<boolean> and then invoke this.followState.next(true)

For instance:

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

Then in your HTML, you can utilize the async pipe.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating an additional ion-item alongside the existing one instead of substituting it

I am retrieving a list of questions from an API with pagination. I have a button that triggers a function to load the next page of questions. Instead of replacing the previous page, I want to append the new questions below the existing ones. Here is my cur ...

Unable to consolidate subdocument's collection

Having the following documents: I am facing a challenge where I need to aggregate the latest rating from the last array element and then calculate the average of (3,1,3,1). Currently, I am struggling with double unwind and unable to obtain the desired res ...

Tips for styling the json response received from a servlet with jquery ajax

I am attempting to display a list of users returned from a servlet using jQuery ajax. The first script block is functioning well, successfully presenting the list of users in a formatted manner but experiencing issues passing form parameters such as text a ...

Accessing specific elements within multi-dimensional arrays using JavaScript

I've embarked on the exciting journey of creating my own 'Choose Your Adventure!' game, but I've hit a snag. I'm struggling to effectively target specific values within the multi-dimensional array I constructed. In order to add som ...

Exploring Videogular Integration with Angular 2 through the VgAPI

My experience with Videogular2 has been interesting as I am attempting to play and control multiple videos simultaneously. The documentation suggests using a master and slave video setup to control both videos with the same controls, but this approach lim ...

Incorporating JSON data on-the-fly into a space tree visualization

I'm currently utilizing spacetree js to display the tree view. My goal is to dynamically load the json data after clicking on a node. I have tried running the sample examples with hardcoded json values. However, I am unsure of how to make it more d ...

Achieve uninterrupted deployment of node.js applications by utilizing naught for zero downtime implementation

Recently, I began utilizing naught for deploying my node.js applications (https://github.com/andrewrk/naught). In my Ubuntu Server, I have a directory that contains my node.js (express) app. To deploy it, I used the command "naught start app.js" from tha ...

Is there a way to implement a polyfill for DOMParser on Web Worker in order to utilize it for uploads with the AWS S

Our team has implemented the AWS S3 SDK for uploading files from a browser to S3 buckets. To prevent UI rendering and interaction issues caused by large file uploads, we decided to move the upload process into a Web Worker thread. This solution allows user ...

How can I query for names that contain both the letters A and X using mongoose?

Using Mongoose, I am looking to utilize the find() method with two different strings. In my database, I have 'Mr. Robot', but if a user types 'Mr Robot' without the dot, nothing is returned due to the difference in the string. To addres ...

The key property is present on the list item, yet the key warning persists

I have encountered various issues with this problem, but I am unable to pinpoint the exact cause. I am not extracting individual list items and simply displaying a UL with unique keys assigned to each item. However, when I log the results, I see something ...

Having trouble retrieving information from .pipe(map()) method

Encountering some issues with Observable handling. I have a function that returns an Observable. public getData(userId) { const data = this.execute({userId: userId}); return {event: "data.get", data: data} } private execute(input: SomeDt ...

Numerous mistakes detected in the TypeScript code

I've implemented the following class within an ASP.NET Core React application: import * as React from 'react'; interface MyInputProps { inputType: string; id: string; className: string; parentFunctio ...

Lazy loading implemented with BootstrapVue's b-nav component

Having some trouble wrapping my head around the following issue: I've created a Vue.js component with tabs that have routes. I opted for a variation of the b-nav Tabs style (official docs) and it's functioning well in terms of tabs and routing. ...

Basic javascript doesn't trigger

Attempting to create a basic AJAX script for testing PHP functionality. However, experiencing issues as the expected output "here" is not appearing due to an error message regarding event.returnValue being deprecated in Chrome. Any insights on what may be ...

Notify other components in Angular when a change has occurred without relying on intervals

In the footer component of my project, I currently have a code snippet that runs a check on LocalStorage every 15 seconds using a timer. ngOnInit() { const checkLocalStorage = interval(15000); checkLocalStorage.subscribe(data => { ...

Using Three.js to apply a sprite as a texture to a spherical object

function generateLabel(icon, labelText, labelText2, labelText3, bgColor, fontColor, transparency, xCoordinate, yCoordinate, zCoordinate){ $('#imglabelcontainer').append('<div class="imglabel" id="imglabel'+labelText+'" style ...

Exploring the power of AngularJS through nested directives

Index.html: <nav-wrapper title="Email Test"> <nav-elem value="first"></nav-elem> <nav-elem value="second"></nav-elem> </nav-wrapper> app.js: app.directive('navWrapper', function() { return { ...

Angular JS Sorting Wordpress Plugin allows users to easily organize and sort content

Seeking some assistance here, any help would be greatly appreciated. Currently using a Wordpress Angular JS plugin that is causing some unusual alphabetical sorting. This snippet of code showcases the taxonomy: <!-- for taxonomy --> <div ng-if ...

AngularJS is making sure that the JSON data being posted has been successfully transmitted

I'm attempting to transfer data from an AngularJS app to a PHP script to then insert it into a MySQL database. I have the necessary files - index.html with the script, getUser_api.php, and insert.php. Although there are no errors in the console, I&ap ...

The Angular 7 template falls short of occupying the entire page

I am currently working on converting an HTML page into my Angular project. While it functions correctly in the HTML version, it does not fill up the entire page when transferred to Angular. You can view an example of this issue on StackBlitz at the followi ...