Check if a Firestore document exists and display a button in Angular based on the boolean result

Seeking desired outcome:
How to display a button in an Angular view based on the boolean value returned by an Angular Service that checks for the existence of a Firestore document.

Current Scenario
The Service successfully verifies the presence of the document and updates the global variable within the if/else statement. While I can log the boolean value when calling the function in the service, it is not being returned as expected.

Challenge
Upon invoking the function from the component, it consistently logs [object Promise] and triggers a TS lint error:

Type 'Promise<Boolean>' is not assignable to type 'boolean'.

What steps can be taken to address this issue? Is it necessary to convert the promise into a boolean or an Observable?

Service Implementation:

export class ProfileFollowService {
    
    // Global variable meant for update
    followState: boolean;
    
    // Verifies document existence and returns a boolean
    async checkFollow(followingID: string, followerID: string): Promise<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;
    });
  }
  
  async callCheckFollow(followingID: string, followerID: string) {
  
    const result = await this.checkFollow(followingID, followerID);
    console.log(result); //Logs true or false as intended
    return result;
  }

}

Component Class:

export class ServiceTestComponent implements OnInit {

  followState: boolean;
  
  constructor(private followService: ProfileFollowService) {

    // Raises TS Lint error: Type 'Promise<Boolean>' is not assignable to type 'boolean'.
    this.followState = this.followService.callCheckFollow('someID', 'someID');
    
    // Logs [object Promise], instead of true or false
    ngOnInit() {console.log('followstate' + this.followState);}

}

Component HTML:

<div *ngIf="followState === true">
  <p>hello Doc</p>
</div>

<div *ngIf="followState === false">
  <p>No doc</p>
</div>

Answer №1

In a typescript component, there is a boolean property being assigned to a Promise inside the constructor.

To properly handle this, move the code to the ngOnInit method. Add the async keyword before the method and use the await keyword before assigning the value to the followState variable.

export class ServiceTestComponent implements OnInit {

  followState: boolean;

  constructor(private followService: ProfileFollowService) { }

   // logs [object Promise], should log true or false
   async ngOnInit() {
     console.log('followstate' + this.followState);

     this.followState = await this.followService.callCheckFollow('someID', 'someID');
   }


}

Answer №2

Trying a bit of blind coding here, do you think this approach could work?

In this service, Rxjs is utilized to check if the object exists and return an Observable with dynamic snapshot changes:

public verifyFollow(followingID: string, followerID: string): Observable<boolean> {
    return of(this.angularFirestore.collection('users/${followingID}/following').doc(followerID).snapshotChanges().take(1).do(d => d.payload.exists));
}

In the TypeScript Component, simply obtain the observable from the service.

export class TestingComponent implements OnInit {

  followState: Observable<boolean>;

  constructor(private followService: ProfileFollowService) {
     this.followState = this.followService.verifyFollow('someID', 'someID');   
   }
}

Then in the HTML, listen asynchronously for changes in the follow state.

<div *ngIf="(followState | async)">
  <p>Hello Document!</p>
</div>

<div *ngIf="(!followState | async)">
  <p>No document found.</p>
</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

Issues arising from the integration of multiple GraphQL resolver implementations in NestJS

After diving into the world of NestJS and GraphQL, I decided to start my journey by creating a resolver class called UserResolver in the UserModule. This class allowed me to retrieve a list of users or a specific user using methods decorated with @Query(). ...

Utilizing Angular Validators.email with the ability to accept null values

In my .ts file, I have an Angular validator set up like this: this.detailsForm = formBuilder.group( { email: ['', Validators.compose([Validators.email])] }); While this setup works fine, the email validator also applies the required validat ...

Storing pictures in MongoDB as binary large objects using React

I have been working on utilizing the dropzone-react component for uploading images. Upon successful upload, it provides me with the blob:http://test address which allows me to view the uploaded image. However, I am facing a challenge in saving this image a ...

Error message occurred stating "error running npm start due to spawn C:WINDOWSSystem32WindowsPowerShellv1.0powershell ENOENT"

Whenever I attempt to run npm start, this is the issue that arises. It seems like there might be a problem with PowerShell rather than npm because npm successfully starts the development server. By the way, I created a basic React app using npx create-reac ...

Is it possible to showcase D3 charts on an .epub file?

For my research project, I am exploring the possibilities of .epub files and experimenting with embedding JavaScript code to display data visualizations. I am currently using calibre to convert an HTML file containing D3 scatterplots into an .epub. The s ...

Bring life to the process of adding and removing DOM elements through animation

I am seeking to provide an engaging and interactive experience for my users while ensuring responsiveness. To achieve this goal, I have decided to learn more about web development by creating a card game. My current setup involves clickable elements that ...

I need to display the product name associated with the product_id found in the line_items array within the order table. I aim to achieve this functionality by utilizing Laravel with Vue.js

In my database, there is a cell called line_items in the orders table that contains data like: [ {"customer_id":"30","product_id":"10","unit_id":"2","quantity":"1","price":"2700","total_price":"2700"}, {"customer_id":"30","product_id":"43"," ...

There seems to be an issue with loading objects using the binary loader in three.js

I have been working on customizing the code of a three.js example to load a .js file that was originally in .obj format. I am using BinaryLoader.js to load the object, however, the object is not appearing in my modified code. Here is what my code looks lik ...

When using TypeScript, the tls.TLSSocket() function may trigger an error mentioning the absence of a "socket" parameter

Currently, I am in the process of building a basic IRC bot and using raw sockets to connect to the IRC server. Initially written in plain Javascript, I am now transitioning it to TypeScript. However, I have encountered an unusual issue when attempting to c ...

What is the best method to set one div as active by default in jQuery UI Accordion?

$(window).load(function(){ $.fn.togglepanels = function(){ return this.each(function(){ $(this).addClass("ui-accordion ui-accordion-icons ui-widget ui-helper-reset") .find("h3") .addClass("ui-accordion-header ui-helper-reset ...

What is the best way to organize variable values in conjunction with their corresponding variable names?

Among the 7 variables - rodeo, saya, balthazar, mistral, luna, calypso, and kiara - each holds a value obtained from calculations in the initial part of my program. My goal is to arrange these variables in ascending order based on the values they contain, ...

Discover the worth within the outcome obtained from the AJAX request

I have an action that returns a tuple containing a boolean value and a string. How can I retrieve the first boolean value from the result, which could be either true or false? This is the action: public Tuple<bool, string> Check This is the AJAX c ...

"Implementing real-time form validation in React with onChange

I am currently facing an issue with form validation in React that has me stumped. Here's the problem: I need to check if two input fields are matching, for example, validating if a user did not make a typo in their email address. However, I want this ...

command that fails to execute when a user is tagged

I've been working on a code snippet that generates a Rich Embed displaying the Avatar of a mentioned user or the message author if there is no mention. The interesting thing is, the code functions properly without a mention, but fails to work when men ...

Chrome browser exhibits a phenomenon where the Bootstrap modal will erroneously print the same page multiple times based on the

When I open a modal, there's a print button inside it. I've researched solutions provided here and here to enable printing of Bootstrap modals, but I'm encountering a Chrome-specific bug. The issue doesn't occur in Safari, Firefox, or E ...

reCAPTCHA 2 triggers an error of 'excessive recursion'

I have decided to incorporate bootstrap 4 into my current Umbraco CMS project. My goal is to integrate reCAPTCHA 2 into a registration form, but I am encountering some difficulties in the process. I have successfully generated the keys for the reCAPTCHA ...

What is the method for selecting multiple items from a list?

Is it possible to select multiple items in the image above? I attempted using http://ionicframework.com/docs/components/#checkbox, but I prefer having checkboxes for multiple selections in Ionic. I am currently working with the Ionic framework and would a ...

Removing a particular item from an Observable of arrays containing any type

My application has an Observable that contains an array of places: places: Observable<Array<any>>; In the template, I am using the async pipe to iterate over the array: <tr *ngFor="let place of places | async"> ... </tr> After ...

Using regular expressions in JavaScript, how can one extract the content along with the HTML tags from within the tags?

Below is the text to be analyzed: how much production in batu The text is displayed with HTML tags where each word is wrapped in a span with a specific style or class. For example: '<span style="">how &nbsp;</span><span style ...

Combining two datasets within a single subscription either renders the set as read-only or allows for modifications to be made to the set in Angular

Hey there! I've been encountering some issues with a service I'm using. It takes a long time to return its result, and to make matters worse, I have to call it twice. The data I receive forms two grids, with one being editable and triggering ev ...