Modifying a variable within an arrow function does not result in the variable being changed when checked outside of the arrow

I am currently developing an application with Angular and Typescript where I need to update the value of a variable inside a function. To retrieve the data required, I'm utilizing a service. Below is the code snippet for reference:

 let isDataAvailable: boolean = false;

  onChangeValue(list: List) {
     this.someService.getData(list).subscribe(
        item => {
        if(item.value === 1) {
            isDataAvailable = true;
          }
       }); 
   console.log(isDataAvailable);          // The value still remains false at this point  
  }

Answer №1

Hello there!

The reason for this behavior lies in the asynchronous nature of your service call. The browser does not wait for the service to emit a value, which is then handled in the subscription block.

isDataAvailable = false;

onChangeData(data: Data) {
    this.dataService.fetchData(data).subscribe(response => {
        if (response.value === 1) {
            this.isDataAvailable = true;
            this.updateCallback();
        }
    });   
}

updateCallback() {
    console.log(this.isDataAvailable); // true
}

You need to handle it in a similar manner as shown above. Hopefully you understand now (you can also search about javascript event loop for more insights).

Answer №2

Given that Javascript operates asynchronously, the value will only update once the getData service call is completed.

In this scenario, the console output occurs before the getData operation takes place.

To address this issue, you have the option to utilize promises or callbacks.

See an example below:

isValue:boolean = false;

onChangeValue(list: List) { 
   onDataRecieved((res)=>{
     console.log(this.isValue);
   });    
}       

onDataRecieved(cb){
 this.someServive.getData(list).subscribe(
      item => {
      if(item.value === 1) {
         this.isValue = true;
         cb(true);
      }
   });
}

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

Identifying a specific field in a dynamically generated React.js component: Best practices

Currently, I am in the process of developing a form with an undetermined number of sensor fields. The front end has been successfully implemented and now my focus is on extracting user information from these dynamically generated component fields. Here is ...

"Creating a dynamic Map using the HERE Maps API and adjusting its size: A step-by-step guide

I am currently working on a Website project and I am interested in incorporating an interactive map from HERE Maps that spans the entire screen under my navigation bar. How can I achieve this? After initially using Google Maps, I switched to HERE Maps due ...

Determining if an element is present in a JavaScript array and returning true

I've come up with this code so far: var isMatch = viewedUserLikedUsersArray.indexOf(logged_in_user); if (isMatch >=0){ console.log('is match'); } else { console.log('no match'); } When an element is ...

What is the best way to delete a particular CSS class using jquery?

My task is to remove the "btn" class from items that have an additional argument in their class name, such as: <input type="button" class="btn btn-mini btn-success email-user" id="emailid5" value="Email Tester"> I specifically need to only remove t ...

Incorporating Material and Formly components into an Angular library

While attempting to develop an Angular 9 library that incorporates Material and Formly modules, I am encountering difficulties in configuring it. Within the library: core-ui.module.ts /** * Angular Core */ import { CommonModule } from '@angular/c ...

Incorporating JSON into a Yahoo! widget

Help! I was reading the Yahoo! Widgets spec and it mentioned that I can parse JSON objects using JSON.parse(). So, being curious, I tried it out with this code snippet... var parsed = JSON.parse('{"key": "value"}'); console.log(parsed); for ( ...

Issue with vue-apollo package causing GraphQL query not to display on the frontend

Currently, I am expanding my knowledge of GraphQL and working on a project where I aim to display queries in the front end. To achieve this, I have incorporated the package GitHub - Akryum/vue-apollo: ...

Utilizing Angular-dependent subscriptions in conjunction with forkJoin for efficiently modifying and processing data within code blocks

I have a subscription that relies on the outcome of a previous subscription. I am utilizing forkJoin to avoid nesting them: this.service.service1().pipe( flatMap((res1) => this.service.service2(res1)) ).subscribe((res2) => { // Perform actio ...

"Upon populating an object with Mongoose, the return value is an

Recently, I set up a mongo database and created a Post model that has a reference to the User by _id. I wanted to retrieve information about the posts a user has made, so I implemented a callback function within exec() while populating the selected User. H ...

Resultant vector

Having trouble calculating the resultant of 3 vectors. Every time I input a number, it returns NaN. Can someone shed some light on this? var vector1 = document.getElementById("f1"); var vector2 = document.getElementById("f2"); var vecto ...

Top techniques for creating a popup window with React

I'm working on my React application and I'm looking to implement a popup window that displays a table with some data. However, I want this popup to appear in a separate browser window rather than as a modal attached to the application's DOM. ...

Associate a click event to a dropdown menu element to trigger on selection

My issue involves having multiple select elements. When one of them is changed, I am trying to bind a click event only to its next element with the .btn class. Below is the code snippet illustrating my problem: <div class="whole"> <ul> ...

Comparing background-color using .css() in jQuery/Js

I've been experimenting with creating angled divs on a webpage, where each basic panel is separated by an angled break. The idea is to have the background-image of one div flow smoothly into the background-color of the next div. Since I couldn't ...

What is the interaction between a service worker and a sub-domain?

I have been exploring how Angular 6 works with ngsw-config.json for service worker configuration, but I'm unsure about its interaction with sub-domains. Based on my current understanding: When a user visits example.com, The service worker is regist ...

Angular 12 experiencing CSS alignment issues

In my Angular component, I have the following CSS: .folders { border-left: 5px solid #b8744f; -moz-border-radius: 5px; -webkit-border-radius: 5px; -moz-box-shadow: inset 0 0 1px #fff; -webkit-box-shadow: inset 0 0 1px #fff; /*CORRECTION NEEDED ...

If a single checkbox is selected within a group, then every other checkbox should be deactivated and deselected

Here is the code snippet provided: function listen(element, event, callback) { if (element.attachEvent) { element.attachEvent('on' + event, callback); } else { element.addEventListener(event, callback); } } var form = document.que ...

Error: Router service provider not found in Angular 2 RC5!

Having trouble with using this.router.navigate. Here is the content of my app.module.ts file: import {NgModule, NgModuleMetadataType} from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; im ...

Deactivate every checkbox in a row within an array

Seeking assistance with disabling a specific checkbox within a row. For example, Consider the following scenario {availableBendsHostnames?.map((bEnds, indx) => ( <div key={indx}> <div>B-End: {bEnds}</div> ...

Tips for maintaining an updated array's consistency on page refresh in Vue.js?

HelloWorld.vue Dynamic routing in Vuejs: <template> <div> <b>Vuejs dynamic routing</b> <div v-for="item in items" :key="item.id"> <b>{{ item.id }}.</b> &nbsp;&nbsp;&nbsp; <rou ...

Unable to globally install @angular/cli using Node.js on Red Hat software collection

After installing node.js 8 from Red Hat Software Collection (rh-nodejs8), I encountered an issue where I couldn't globally install TypeScript or @Angular/CLI because my bash session was restricted by scl-utils, requiring admin rights for global instal ...