Why isn't my Angular/Typescript Subscription causing a change in the variable for my Arrow function?

Why Isn't My Arrow Function in Subscription of Observer Changing the Local Variable bool?

upVoteAvailability(i: number) {
    let bool!:boolean ;
    this.featureService.upVoteAvailable(i).subscribe(x=> {
      bool = x as boolean
      console.log(bool);//true
    })
    return bool//undefined
  }

Are there any other ways for an observer to update a variable?

Answer №1

Your subscribe function is designed to be asynchronous, meaning that when the

this.featureService.upVoteAvailable(i)
method is invoked, the code will continue executing without waiting for the Observable result.

As a result, you must wait for the Observable to provide its response before proceeding.

There are multiple methods available to handle this situation.

One approach is to utilize async/await functionality.

async checkUpVoteAvailability(i: number) {
    let isAvailable!:boolean;
    await this.featureService.upVoteAvailable(i).toPromise.then(response => {
      isAvailable = response as boolean;
      console.log(isAvailable); //true
    })
    return isAvailable; //true
  }

By using async/await, the execution is paused until the desired value is received. This method relies on Promises for handling asynchronous operations.

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

Is it possible for web browsers to set a timeout on an XmlHttpRequest while it is still active?

When dealing with asynchronous XMLHttpRequests that take a long time to retrieve data from the server, I am searching for a way to abort them. Setting a timeout before sending the XHR is not feasible due to the length of these requests. Although calling X ...

What is the best way to insert a JavaScript button before an HTML button on a webpage?

Currently, I am working on creating a calculator using JavaScript and HTML. My goal is to add memory buttons (MS, MC, MR) before the clear button (C) on the calculator interface. Despite trying various methods, I am facing some challenges in achieving this ...

I'm encountering an issue with my array in JavaScript while using // @ts-check in VS Code. Why am I receiving an error stating that property 'find' does not exist on my array? (typescript 2.7

** update console.log(Array.isArray(primaryNumberFemales)); // true and I export it with: export { primaryNumberFemales, }; ** end update I possess an array (which is indeed a type of object) that is structured in the following manner: const primar ...

There seems to be a problem with completing the Axios post request in the Javascript Front

My front-end, built with React, is having trouble retrieving data from a third-party API through my Node.js backend. Despite using axios.post request, the response remains undefined and I'm stuck at handling the asynchronous request. It appears that t ...

What is the best approach to alter a user's message depending on the form's ID that was used for submission?

I currently have two separate screens that each serve a specific purpose, where only one can be open at any given time. First is the login form: <form action="/Account/Login" id="login-form" class="form" method="post"> <butto ...

"Implementing Google Maps into a React application: A step-by-step guide

I am currently utilizing webpack and reactjs in my project and I am looking to integrate the Google Maps API. First step was to add "react-google-maps": "^4.9.1" in my package.json file. Below is the code for my component class. import React, {PropTypes, ...

Developing a nested JSON structure

I'm struggling with a seemingly simple task of creating a JSON object. Despite my efforts, I can't seem to find the right information to guide me through it. Here is what I have so far: var myJsonObject = new Object(); myJsonObject.context.appli ...

Is there a way to iterate through objects and update their values safely in typescript?

While utilizing Typescript, I encountered the issue described below. My intention was to iterate through an object and modify its values. Despite the functionality working smoothly, Typescript flagged it with an error. How can I resolve this Typescript ...

Angular ngFor not displaying the list

I'm encountering an issue with my HTML page where I'm using NGFor with an array. The error message I receive is as follows: landingpage.component.html:142 ERROR Error: Cannot find a differ supporting object '[object Object]' of type &ap ...

Why is my useState value resetting when I invoke the onPress function?

In my React Native component, I am utilizing a useState hook named tripState. const [tripState, setTripState] = useState<NewTripState>({ name: "", description: "", thumbnail: "", }); I update its value in a ...

The issue with object alignment in the camera rotation is not properly centered in the Three.js framework

After bending two meshes into a circle to create a 3D marquee, I'm facing issues with centering them to the camera. For the full code, please visit https://jsfiddle.net/siiiick/1jh49e1u/ var text = "EXPRESS FREE SHIPPING WORLDWIDE OVER 200€ / ...

Pass along the value of a link upon clicking on it

I have implemented a simple list using md-data-table: <tr md-row md-select="device" md-on-select="logItem" md-auto-select="options.autoSelect" ng-repeat="device in devices.data"> <td md-cell style='text-align:left;vertical-align:middle&apo ...

I'm currently learning about things that never change and struggling to grasp their meaning

I'm currently delving into the world of immutable.js record and trying to wrap my head around it. However, this particular piece of code is really throwing me for a loop. Here's my Question: I understand [import, export,const], but what ex ...

Querying across multiple MongoDB collections with intricate conditions

Recently started working with node and mongo. Coming from a relational db background as a developer. I've been tasked to create a report that calculates the conversion rate from leads related to vehicle workshop bookings to invoices. A conversion is ...

"Exploring the depths of PHP: Generating a JSON string from an array

I am trying to work with PHP code in an Object-Oriented manner and the values I am getting are objects. However, I need to convert these O.O.P objects into JSON data for use by JavaScript. So, I converted my objects into arrays on the PHP end, but when I t ...

Error message: Missing dependency in React useCallback linting documentary

Within my component, I have integrated a custom hook called useInstantSearch. However, when I try to wrap it in useCallback, an error occurs: I receive the message - React Hook useCallback received a function whose dependencies are unknown. Pass an inline ...

I utilized Bootstrap to validate the form, however, despite the validation, the form is still able to be submitted. What steps can I take to

I have implemented form validation using Bootstrap's 'needs-validation'. However, I am facing an issue where the form still gets submitted even when the validation fails. What I want is for the form submission to be prevented if the validati ...

Creating an array dynamically in response to an AJAX call

Is there a way to dynamically create an array after receiving an AJAX response? Upon getting the AJAX response, the variable data.villages contains the data. To iterate over its values, the jQuery each function can be used: $.each(data.villages, functio ...

Angular - ng-class - dynamic progress tracker

I am currently developing a multi-step wizard in AngularJS that consists of three states. Each state should correspond to specific steps being active in the wizard. I have attempted to achieve this by assigning a class of 'active' to each step ba ...

My software consistently triggers the default servlet

I'm encountering an issue with calling a servlet and I could use some assistance. Here is a snippet from my web.xml file: <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.s ...