Unable to retrieve data list in Angular TypeScript

After sending a request to the server and receiving a list of data, I encountered an issue where the data appears to be empty when trying to use it in another function within the same file.

The code snippet below initializes an array named tree:

tree:any[]=[];

intialDataa(): any {
    this.claimsManagerService.getAll(this.searchParam).subscribe(data => {
        this.tree = data['records'];
        })
}

However, when attempting to access this data in a different function:

    openAdd(id, par, title, nodel): void {
    console.log(this.tree)
    }

The console output shows an empty array [].

Further investigation revealed that during the IntialData() function, the tree array contains the following data:

  (74) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
length: 0
__proto__: Array(0)

What could be causing this issue and how can I successfully access the tree data?

Edit: Full Code:

    intialDataa(): any {
    // Code for initializing data...
    this.loading = true;
    // More code for retrieving and processing data...
    this.tree = ddata;
}

Here is the second function:

    openAdd(id, par, title, nodel): void {
    // Code for opening and handling data...
}

HTMl Code :

    // HTML code for displaying data...

Answer №1

this.tree variable is set asynchronously. This means that when you attempt to access it in the openAdd() function, it may not have a value yet. To solve this issue quickly, consider moving the call to set this.tree directly inside the openAdd() function.

openAdd(id, par, title, nodel): void {
  this.claimsManagerService.getAll(this.searchParam).subscribe(data => {
    this.tree = data['records'];
    console.log(this.tree);
  });
}

An alternative approach to enhance the implementation involves using multicast observables like RxJS BehaviorSubject. However, further information about how the functions are triggered would be helpful.

Answer №2

https://i.sstatic.net/q4qZv.jpg

It appears that you have restructured the assignment for this.tree = ddata

Please eliminate the line this.tree = ddata and test it again...

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

The controller's AngularJS function seems to be unresponsive

Issue with AngularJs ng-click Event I'm attempting to utilize the GitHub Search-API. When a user clicks the button, my Controller should trigger a search query on GitHub. Here is my code: HTML: <head> <script src="js/AngularJS/angula ...

What are your thoughts on combining a JSON object with HTML?

When using ASP.NET MVC, it is possible to return a JSONResult. return JSON(new { View = RenderViewAsString("MyView", model), wasSuccessful = true}) This approach combines HTML and data in a single JSON object. The goal is to utilize strongly typed HtmlHe ...

Refactor and rename with VSCode and TypeScript without having to manually open the files being affected

When working with a TypeScript application in Visual Studio Code, is there a way to rename a variable or function without the affected files automatically opening in the Editor area? I prefer my refactorings to be applied immediately and the affected file ...

The power of Vue reactivity in action with Typescript classes

Currently, I am working on a Vue application that is using Vue 2.6.10 along with Typescript 3.6.3. In my project, I have defined a Typescript class which contains some standard functions for the application. There is also a plugin in place that assigns an ...

Angular 14 is throwing an error due to an indent issue - the expected indentation is 2 spaces but 4 spaces were found

Currently using "eslint": "^8.23.0" with angular 14. Everything was functioning properly with "eslint": "^8.22.0", but after updating to 8.23.0, I encountered the following error: https://i.sstatic.net/UALvS.png ...

Styling Descendants Conditionally in Angular 2

.parent { color: blue; } .parent * { color: red; } .child { color: black; } .grandchild { color: green; } <div class="parent"> Parent <div>Child <div>GrandChild</div> </div> </div> Imagine a scenari ...

determine the values of objects based on their corresponding keys

Still on the hunt for a solution to this, but haven't found an exact match yet. I've been grappling with the following code snippet: interface RowData { firstName: string; lastName: string; age: number; participate: boolean; } c ...

Panning or dragging on Google Map V3 can become unresponsive when the cursor moves outside of the map element

I have incorporated a Google map in a specific section of my webpage. I am facing an issue where if I click and drag the mouse outside the map area to other div elements, releasing the mouse still causes dragging/panning to continue when I return to the m ...

Utilizing AJAX within a Rails application to dynamically alter a database field without the need for a traditional form

I am facing a scenario where I have implemented a table with certain rows structured as follows: <div class="row chord-table-row" id= <%= "chord-#{chord.id}" %>> <div class="small-1 columns"><%= chord.id %></div> < ...

Is there a way to locate the final element in a specific angular ng-repeat loop subset?

The final entry in the labels section may not be checked, making $last unsuitable for this scenario. This results in the following sequence: peaches, bananas, cherries, watermelon, How can I locate the last item in an angular ng-repeat loop while using an ...

Utilize specific Angular JS methods just a single time

In my Angular application, I have the following architecture: Index Page -> Shell Page -> User view (User can open subview from here) Every route change in my application goes through the Shell page. There is a function on the Shell page called act ...

Contrasting gatsby-theme-material-ui and gatsby-plugin-material-ui

I'm in the process of creating a website using Gatsby, and I'd like to incorporate Material UI, but I'm unsure about which plugin I should use. Here are my questions: What is the difference between these two options, and how can I integra ...

The blocking of the HttpPost ActionResult due to the deprecation of synchronous XMLHttpRequest

After adding jquery references to my project, I encountered an issue where the Post from a View is not triggering. The Post ActionResult used to save user-chosen settings, but now a break point inside the Post isn't being hit. Visual Studio does not s ...

Create a directive for AngularJS that utilizes SVG elements without using the deprecated

I rely heavily on directives for creating and manipulating intricate SVGs. With the deprecation of "replace" in directive factories starting from version 1.3.??, I am facing a dilemma on how to construct a valid SVG without utilizing replace: true in my di ...

Manipulating JSON Elements using JavaScript in HTML

My objective is to alternate the visibility between the "prev" and "ext" elements retrieved from the JSON File in the following manner: Here is the link to JS Fiddle The menu bar appears as follows: [ "prev_Person1" "Person1" "ext_Person1" ... "Person2" ...

Utilizing JSONLOADER in Three.js allows for efficient loading and

Currently, I am using JSONloader in three.js to load models and it works perfectly. However, I am struggling to find detailed steps or documentation on how to preload textures (which are images) in order to create an interactive feature where I can switc ...

Crack open a JSON object

I am struggling to parse a JSON object. It seems like the code is not working, can you help me? var mock_data = { "available": [{ "UserID": 7, "UserName": "Manoj", "Language": "Java", "Score": 9, "TimeLimit": 4.0 }, { "UserID ...

Converting Abstract Type Members from Scala to TypeScript: A Handy Snippet

I have a brief example of a value level and type level list in Scala sealed trait RowSet { type Append[That <: RowSet] <: RowSet def with[That <: RowSet](that: That): Append[That] } object RowSet { case object Empty extends RowSet { t ...

The connection between Cognito identity and Mqtt is not possible within AWS IoT Core

The application is built using Angular. Upon logging in with Cognito, the application retrieves the user's CognitoUser data, including id token, access key, and session token. Next, the application connects to Iot Core to subscribe to or publish data ...

When Ajax responseText and echo fail, the header file contents are sent back instead

I have a section of code in my PHP file called thePhpFile.php that is used to handle an Ajax call: <?php require_once('usefulStuff.php'); // includes useful functions if (isset($_GET['zer'])) { $bFound = false; if(! $bF ...