The data stored in the variable cannot be accessed when calling it in a different method

Within my component, there are several methods including constructor(){...} and ngOnInit(){...}. I have declared a variable named values:any=[] in the class, and it is initialized with JSON data within a method called getData().

getData(){
  this.service.getData().subscribe(res=>{
    this.values = res.json();
  })
}

I then call this getData() method in ngOnInit(){...}. After this call, I observe that values is indeed populated with data. However, when I try to access values in another method for displaying purposes, it shows up as an empty array.

export class AccountComponent implements OnInit {

  values:any=[];

  constructor(private service: AccountService) {
  }

  getData(){
    this.service.getData().subscribe(res=>{
      this.values = res.json();
    })
  }

  callData(){
       console.log(this.values)  
   } 

  ngOnInit() {
    this.getData();
    this.callData();
  }

In the callData() method, I use console.log(), which displays that values is empty. But why does this happen?

Answer №1

It's true, you won't be able to retrieve data because the http call to get the data has not yet been completed.

If you want to ensure that data is retrieved in the callData method, you can utilize async/await like so:

 async getData(){
     const res =  await this.service.getData().toPromise();
      this.values = res.json();
  }

  async ngOnInit() {
    await this.getData();
    this.callData();
  }

  callData(){
       console.log(this.values)  
   } 

Essentially, you need to wait for the serverside call to finish before proceeding. Currently, you are not waiting for the serverside call to complete, which is why data is not being retrieved in your this.calllData() method.

or

If you prefer not to use async/await, you have an alternative method:

getData(){
    this.service.getData().subscribe(res=>{
      this.values = res.json();
      this.callData();
    })
  }

  callData(){
       console.log(this.values)  
   } 

 ngOnInit() {
    this.getData();
  }

Answer №2

Here's an additional solution I've used in a similar case: implementing the 'setTimeout' function.

  getData(){
    this.service.getData().subscribe(res=>{
      this.values = res.json();
    })
  }

  callData(){
       console.log(this.values)  
   } 

  ngOnInit() {
    this.getData();
    setTimeout(() => {
       this.callData();
    }, 10);
  }

By adding a small delay to the code block that relies on values returned in response, you can ensure smooth operation. I personally used a wait time of 1 millisecond and it has always been reliable for me.

Additionally, when traversing JSON objects, consider returning the JSON directly from the service method. To loop through the object without using 'foreach', you can try the following snippet:

for(let key in json){
    let value = json[key];
    //rest of the code
}

I hope this suggestion is helpful!

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

Images appear as plain text in the preview of VUE 3 (with TypeScript)

Currently, I am developing a Portfolio website and have encountered an issue. While everything runs smoothly with npm run dev, the problem arises when I use npm run preview. In this scenario, some of the images within the files named 3dModellingFiles.ts do ...

Having trouble building my Angular 2 app with Angular-cli beta 14, despite it working perfectly fine with systemjs beforeEach

I have been using VSCode on Windows 10 to work on an app developed in Angular 2 final version, which runs smoothly with systemjs. Recently, I upgraded to angular-cli beta 14 webpack version and followed the steps outlined in the upgrade document here. How ...

Unable to reach the margin-left properties of the elements

I am facing an issue in accessing the current margin-left CSS property of the class .circle in the code snippet below. A demonstration of this problem can be found on a website called PLUNKr. The reason I need to access this property is because I have to ...

Issues retrieving data using Ionic 4 native HTTP plugin result in returning an empty

Currently, I am working on an Ionic 4 project where I am attempting to retrieve a JSON array from a URL using the native HTTP for Ionic. However, when I attempt to fetch the data array from the URL in JSON format, I am met with an empty page. The JSON dat ...

Retrieve the Angular Firebase Document and send it back

I have a question related to retrieving a Document from my FireDatabase. The model I am using is for a user, which looks like this: export class User { useremail: string; userid: string; username: string; constructor(usermail: string, use ...

What is the best way to only buffer specific items from an observable source and emit the rest immediately?

In this scenario, I have a stream of numbers being emitted every second. My goal is to group these numbers into arrays for a duration of 4 seconds, except when the number emitted is divisible by 5, in which case I want it to be emitted immediately without ...

Angular 4: Utilizing reactive forms for dynamic addition and removal of elements in a string array

I am looking for a way to modify a reactive form so that it can add and delete fields to a string array dynamically. Currently, I am using a FormArray but it adds the new items as objects rather than just simple strings in the array. Here is an example of ...

Splitting the div into two columns

I've encountered various solutions to this issue, but when I integrate an Angular2 component inside the divs, it fails to function properly. Here is my progress so far: https://i.stack.imgur.com/qJ8a9.jpg Code: <div id="container"> <div ...

How to implement a reusable module with distinct routes in Angular

In my current angular project, we have various menus labeled A, B, C, D, and E that all utilize the same module. Specifically, menus A, C, and E use the same component/module. My goal is to ensure that when I am on menu A and then click on menu C, the sa ...

After refreshing, the LocalStorage in Angular 2 seems to disappear

Something a little different here :) So, when attempting to log a user in, I am trying to store the access_token and expires in localStorage. It seems to be working "okay". However, if I refresh the page, the tokens disappear. Also, after clicking the log ...

Angular 8 feature module routing encompasses various components working together collaboratively

I am currently working on integrating a main module and a feature module that consists of various components. Below, I have provided the configuration for multiple routes within the feature routing file. const priorityRoutes: Routes = [ { path: &a ...

What is the best way to map elements when passing props as well?

In my code, I am using multiple text fields and I want to simplify the process by mapping them instead of duplicating the code. The challenge I'm facing is that these textfields also require elements from the constructor props. import React, { Compon ...

What is the proper way to declare app.use using TypeScript with the node.js Express module?

I am working on a node.js app that utilizes typescript with express. In my code, I have defined an error middleware function as shown below: app.use((error:any, req:Request, res:Response, next:NextFunction) => { res.status(500).json({message:error.m ...

Tips for enlarging the font size of a number as the number increases

Utilizing the react-countup library to animate counting up to a specific value. When a user clicks a button, the generated value is 9.57, and through react-counter, it visually increments from 1.00 to 9.57 over time. Here's the code snippet: const { ...

What causes TypeScript to be unable to locate declared constants?

I am facing an issue with the following simple code snippet: const getMethod = 'get'; const postMethod = 'post'; export type RequestMethod = getMethod | postMethod; When I try this code in TypeScript Playground, it shows an error sta ...

Solution: How to fix the error: Invalid component type, 'Draggable' cannot be used with JSX in react-draggable

I encountered an error while working on this Next.js React project Type error: 'Draggable' cannot be used as a JSX component. Its instance type 'Draggable' is not a valid JSX element. The types returned by 'render()&apo ...

Tips for creating a sophisticated state transition diagram using Typescript

If you have a creative idea for a new title, feel free to make changes! I have two enums set up like this: enum State { A = "A", B = "B", C = "C" } enum Event { X = "X", Y = "Y", Z ...

Resetting the selected value in an Angular2 select element after the user makes a change

I have a dropdown menu which the user can select an option from. Initially it has a default value and when the user makes a new selection, I need to ask for confirmation by showing a message "are you sure?". If the answer is NO, then I should revert back t ...

Ways to eliminate the white background gap between pages on ionic

While developing an app using Ionic, I encountered a strange issue. Everything runs smoothly on a browser, but when testing the app on an Android 5 device, I noticed a white background appearing between pages. The app loads correctly with the custom splas ...

Decide on the chosen option within the select tag

Is there a way to pre-select an option in a combobox and have the ability to change the selection using TypeScript? I only have two options: "yes" or "no", and I would like to determine which one is selected by default. EDIT : This combobox is for allow ...