Asynchronously retrieving data in .NET using Angular

Initially, I am attempting to retrieve all projects from the database based on the provided userId from the URL. This operation is performed in the ngOnInit() lifecycle hook. Each project contains a field named Languages, which represents a list of objects from another table called Languages. Each record in the Languages table includes a field called projectId, which I use to fetch all languages for each project. It seems like I am encountering an issue with data being retrieved asynchronously, as the projects are fetched correctly but the languages field within each Project object is null. What steps should I take to resolve this?

ngOnInit() {
    this.userId = this.route.snapshot.params['id'];
    this.getAllProjectsByUserId(this.userId);
    this.getLanguagesByProjectId();
  }

  getAllProjectsByUserId(id: number) {  // Receives all projects based on the provided userId
    this.portfolioAppService.getAllProjectsByUserId(id).subscribe((data) => {
      this.projectsList = data;
      console.log(this.projectsList);
    },
      error => console.error(error)
    );
  }

  getLanguagesByProjectId() {  // Retrieves all languages for each project
    this.projectsList.forEach(x => {
      this.portfolioAppService.getLanguagesByProjectId(x.id).subscribe((data) => {
        x.languages = data;
        console.log(this.projectsList);
      },
        error => console.error(error)
      );
    });
  }

Answer №1

Ensure to call getLanguagesByProjectId() only after receiving the projects:

  getAllProjectsByUserId(id: number) {  //getting all projects for a specific userId
    this.portfolioAppService.getAllProjectsByUserId(id).subscribe((data) => {
      this.projectsList = data;
      console.log(this.projectsList);
      this.getLanguagesByProjectId();
    },
      error => console.error(error)
    );
  }

Otherwise, this.projectsList property will not have the necessary values yet.

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

send document through ajax

Having some trouble with this task. Here is what I've managed to put together so far: <input id="newFile" type="file"/> <span style="background-color:orange;" onClick="newImage()">HEYTRY</span> I know it's not much progress. ...

Can you explain the distinction between the terms "vite" and "vite preview"?

I recently created a project template with the help of vite. While looking through my package.json file, I noticed the following section; "scripts": { "dev": "vite", "build": "vue-tsc --noEmit &&a ...

Encountered an error while attempting to install the DataTables npm package in an Angular

I am trying to add datatables to my angular application. Upon running ng add angular-datatables An error code is displayed (refer to the image). error image The cause of this error is unknown to me. Please review the package.json file as well. package.j ...

Methods for presenting text from an object array using Angular

I'm running into a bit of trouble with getting my text to show up properly in my code. In the HTML, I have <td>{{cabinetDetails.cabinetType}}</td> and my data source is set as $scope.cabinetDetails = [{cabinetType: 'panel'}]; De ...

"Converting an HTML file to a Word file using PHP - a step-by-step

Help needed with converting an HTML file to MS Word using PHP code. Below is the code I am using: include("connection.php"); extract($_REQUEST); ob_start(); include("counties/$county_name/$file"); $html_content = ob_get_contents(); ob_end_clean(); header ...

Vue js: Stop Sorting array items; only display the resulting array

I recently came across a tutorial on voting for a Mayoral Candidate. The tutorial includes a sort function that determines the winner based on votes. However, I noticed that the sort function also rearranges the candidate list in real time, which is not id ...

Utilizing an object map to pass objects as props without losing their keys

I have an array of objects named obj, structured as follows: { "root": [ { "key": "mihome", "label": "home", "action": "url", ...

Tool for tracking response time on basic Ajax-requested webpage

Looking for an easy way to use ajax to load content onto a page. I want the loaded content to wait before appearing on the page, but using jQuery's .delay() function didn't work as expected. Any suggestions on how to achieve this? Appreciate any ...

Using Javascript and Regular Expressions to separate and preserve the delimiter

I'm facing an issue with my regex that splits a string into arrays. Everything is working smoothly except for the fact that I want to retain part of the delimiter. This is the regex I am using: (&#?[a-zA-Z0-9]+;)[\s] In my JavaScript cod ...

Enhancing systemjs-builder with DefinitelyTyped

Is there a dedicated TypeScript definition file for systemjs-builder available? https://github.com/systemjs/builder I encountered an issue where the systemjs.d.ts file does not seem to cover it, leading to a "cannot find module" error when trying to impor ...

Specifying the data structure of a complex nested Map in TypeScript

Struggling to create a deeply nested (recursive) Map in Typescript generically. My attempt is to convert the provided Javascript example to Typescript: const map1 = new Map([ ['key1', 'value1'] ]) const map2 = new Map([ ['keyA& ...

Issues with Mega Menu functionality preventing items from being clickable and links from properly navigating

Recently, I encountered a strange issue related to the integration of a mega menu found at . Unfortunately, despite integrating the mega menu, the Category and sub category links seem unresponsive - they are not directing me to the desired links. I suspec ...

Using Three.js to display multiple objects simultaneously causes my browser to crash

When it comes to rendering objects in a scene, I encountered an issue with loading multiple objects. Initially, loading all 3 objects as STL files worked fine. However, when I attempted to divide each object into multiple surfaces and create BufferGeometry ...

What is the process for loading this image?

While browsing through this stunning website, I came across a feature that caught my eye. Can someone please explain how the designer displayed the "The magic is loading" effect: The image vanishes once the site has finished loading completely. ...

What is the recommended return type in Typescript for a component that returns a Material-UI TableContainer?

My component is generating a Material-UI Table wrapped inside a TableContainer const DataReleaseChart = (): React.FC<?> => { return ( <TableContainer sx={{ display: 'grid', rowGap: 7, }} > ...

MDX is revolutionizing Next app routing with the introduction of 'use client' functionality

After setting up MDX with Next.js 14, I encountered an error when navigating to the mdx page: Error: createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. The file mdx-components.tsx is ...

Modify the class of an input while typing using Jquery

Recently, I created a form using Bootstrap 4. The validation process is done through a PHP file with an AJAX call and it's functioning correctly, except for one issue. I want the input class to switch from "invalid" to "valid" as soon as the user begi ...

"Trouble arises when dealing with nested object arrays in Formik and handling changes in a child

I am struggling with passing a value to handleChange in formik validation. To address this issue, I created a component whose quantity is dynamically added based on the number of numChild. My goal is to allow users to click an icon and add any number of sk ...

Develop a module using the Angular plugin within the Eclipse IDE

I am currently new to Angular and following the Angular Get Started Tutorial (https://angular.io/guide/quickstart). I am using the angular cli plugin in Eclipse. As I reached the 7th part of the tutorial, I am required to create a new module with the comm ...

Exploring the concept of named groups within the .NET Regex functionality

As a newcomer to .NET, I'm facing some challenges in grasping the concept of the Regex object. My objective can be outlined as follows. The following is a rough representation since I lack the exact code required for implementation: string pattern = ...