Ways to retrieve a boolean value from my API and implement it

I am facing an issue retrieving data from my backend server.

file.html

<div *ngIf="shouldDisplay">
  <p> information to display </p>
  <button mat-flat-button type="button" (click)="update()">
     update
  </button>
</div>

file.ts

shouldDisplay: boolean;

ngOnInit() {
  this.initialize();
}

initialize() {
  this.fileService.check().subscribe(data => {
    this.shouldDisplay = data;
  });
}

update(){
  this.initialize();
  
  if(this.shouldDisplay){
    this.fileService.update();
  } else {
    this.notificationService.error('errorMessage');
  }
}

I need the 'shouldDisplay' variable to be set as true in the 'check' method response. Also, I want to utilize the 'shouldDisplay' variable in the 'update' method.

Answer №1

When dealing with the asynchronous action of this.check(), it's important to handle the completion by returning the underlying Observable and subscribing to it within other methods:

ngOnInit(): void {
  this.check().subscribe(() => this.shouldDisplay = this.checkData);
}

check(): Observable<boolean> {
  return this.fileService.check().pipe(
    tap(data) => this.checkData = data)
  );
}

update(): void {
  this.check().subscribe(() => {
    if (this.checkData) {
      this.fileService.update();
    } else {
      this.notificationService.error("errorMessage");
    }
  });
}

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

Changing the host domain to a non-.com extension in Angular-cli while serving for development

While running an ng serve on my angular cli build, I am attempting to use a .ca domain as the host in order to address CORS and cookie issues during development. Interestingly, when using a .com domain, everything functions smoothly: Functioning with .com ...

What is the best way to categorize an array based on a specific key, while also compiling distinct property values into a list

Suppose there is an array containing objects of type User[]: type User = { id: string; name: string; role: string; }; There may be several users in this array with the same id but different role (for example, admin or editor). The goal is to conv ...

How to toggle visibility of multiple div elements in ReactJS

When working in react-js, I encountered a situation where two div elements and two buttons were used. Clicking the first button displayed the first div and hid the second div. Conversely, clicking the second button showed the second div and hid the first d ...

The 'subscribe' property is not found in the type 'OperatorFunction<Response, Recipe[]>'

I'm encountering an issue while attempting to retrieve data from firebase "Property 'subscribe' does not exist on type 'OperatorFunction'" Any suggestions on what might be missing here? import { Injectable } from '@angula ...

It is crucial to include the _id field in the findOneAndUpdate operation

In my code, I have a function that updates documents in mongoDB. After manipulating the data, I use mongoose's findOneAndUpdate function to update the desired document. To fetch only specific fields from the saved data, I set new:true and define an ob ...

What could be preventing me from setting a boolean variable within an Observable?

After retrieving data from the Service, I am attempting to hide a specific div element. Below is the HTML code: <progressbar *ngIf="isLoadingBootStockData" [value]="100" type="default"> </progressba ...

What could be causing the node to run so slowly during a Chrome audit with Lighthouse?

Recently, I put together a simple single-page JavaScript application. Here's the code snippet: // Load HTTP module var http = require("http"); // Create an HTTP server and listen on port 8000 for requests http.createServer(function(request, response ...

Looking for a Regular Expression Validation Pattern!

Is there anyone who can provide insight into how to establish this validation pattern? All sentences must start with a capital letter, and the message should conclude with a full stop. There should be no spelling errors. ...

Upon launching Google Chrome, a series of errors plague the WSL2 Ubuntu setup while running Karma and Jasmine for Angular testing

My Angular project utilizes Google Chrome for testing with Karma & Jasmine, but upon starting Chrome, I encounter multiple errors. Despite trying various solutions found on Stack Overflow, none have been successful. The versions in use are: Chrome 99.0.4 ...

The code in the Node.js/Express application remains unchanged even after making alterations to the source code

I apologize for the unorthodox title of this question. I struggled to find a concise way to describe my current issue. As a beginner in Node.js, I am attempting to create a simple node/express app. Initially, everything was going smoothly as I set up var ...

Retrieving the component function name in Angular production mode after minification

I am facing a unique challenge where I have developed a dynamic page that loads various components based on data retrieved from a database, following the tutorial provided in Angular's documentation. The component names and attributes are stored in th ...

Exploring the dynamic duo of NextJS 14 with SupabaseAuth and the power of SupabasePostgres

As a recent graduate of a Full Stack Bootcamp, I am diving into NextJS and exploring Supabase for authentication. I may have some beginner questions, so bear with me. Currently, I am utilizing a NextJS TypeScript template and incorporating Supabase for au ...

Struggling with keeping radCalendar events up-to-date in NativeScript (Angular)

I'm currently facing an issue with updating events in a radCalendar. I've built a service to modify the eventSource bound to the radCalendar in HTML, but for some reason, adding a new event to that array doesn't reflect on the radCalendar ev ...

A Defer statement in TypeScript that mimics Go's functionality

Is there an equivalent to Go's Defer statement in TypeScript? I find it tedious to write cleanup code in various parts of a function. Searching for a simpler alternative. I tried searching on Google, but couldn't locate any relevant information ...

What is the process for directing to a particular URL using htaccess file?

I recently deployed my Angular and Node project on the same hosting server. Here are the URLs: - Angular project: - Node project: I have set up a redirection for all API requests from to . Below is the .htaccess code I'm using: RewriteEngine ...

What could be the reason behind encountering the UnhandledPromiseRejectionWarning error while executing npm build in my serverless application?

I am encountering an issue while attempting to execute npm build on my serverless aws-nodejs-typescript project. I am unsure of how to resolve it. Can someone provide guidance on how to troubleshoot this problem? npm build (node:44390) UnhandledPromiseRej ...

Organizing an array based on designated keywords or strings

Currently, I am in the process of organizing my logframe and need to arrange my array as follows: Impact Outcomes Output Activities Here is the initial configuration of my array: { id: 15, parentId: 18, type: OUTPUT, sequence: 1 }, { id: 16, parentId: ...

Continuously execute the scroll function as long as the cursor remains over the element

Is there a method to continuously execute a function while the cursor hovers over a specific DOM element? I need to trigger a scroll action whenever the user hovers over an arrow, with an optional timeout feature. This requirement must be met without utili ...

Discover how to validate a property within an array of objects and add the accurate values to a fresh array using TypeScript

I have a list of objects and I want to create a new array that contains only the objects with the 'read' property set to true. I've tried a couple of different methods, but I keep getting an error: Uncaught TypeError: Cannot read properties ...

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 ...