Utilizing Javascript to load and parse data retrieved from an HTTP request

Within my application, a server with a rest interface is utilized to manage all database entries. Upon user login, the objective is to load and map all user data from database models to usable models. A key distinction between the two is that database models solely contain ids of child objects, whereas normal models directly inherit their child objects. To achieve this mapping through http requests and incorporate them into the application, the following structure was implemented:

class SomeClass {
  private loadProjectData(projectId: string): void {
    let s: Sheet;
    let d: Dashboard;
    this.databaseService.getDocument("Projects", projectId).subscribe(
      (project: ProjectDB) => {
        this.project = new Project(project.id, project.name, project.theme, []);
        for (const dash of project.dashboards) {
          this.databaseService
            .getDocument("Dashboards", dash)
            .subscribe((dashboard: DashboardDB) => {
              d = new Dashboard(dashboard.id, dashboard.name, []);
              for (const shee of dashboard.sheets) {
                this.databaseService
                  .getDocument("Sheets", shee)
                  .subscribe((sheet: SheetDB) => {
                    s = new Sheet(sheet.id, sheet.name, []);
                    for (const wid of sheet.widgets) {
                      this.databaseService
                        .getDocument("Widgets", wid)
                        .subscribe((widget: WidgetDB) => {
                          // TODO check widget type
                          s.widgets.push(
                            new Widget(
                              widget.id,
                              widget.name,
                              widget.position,
                              widget.isDeveloped,
                              widget.type,
                            ),
                          );
                          this.dataService.changeProjectData(this.project);
                        });
                    }
                  });
              }
              d.sheets.push(s);
              this.dataService.changeProjectData(this.project);
            });
          this.project.dashboards.push(d);
          this.dataService.changeProjectData(this.project);
        }
        console.log("Project", this.project);
        this.router.navigate(["dashboard"]);
      },
      err => {
        console.log("Error loading project data from database ", err);
      },
    );
  }
}

This code meticulously traverses each hierarchy: Project -> Dashboards -> Sheets -> Widgets. The concept behind this approach is that as each lower-level hierarchical entity is loaded, it's added to the corresponding upper-level parent element. However, upon execution of the code, all objects except for the project turn out to be undefined. Seeking guidance on resolving this issue. Thank you in advance.

Answer №1

Consider analyzing subscription levels as they hold essential data that can be utilized effectively outside of the subscribe callback. Additionally, explore various rxjs methods like combineLatest and switchMap to refactor this code into a more developer-friendly structure.

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

Angular cookies may expire, but using the back button always revives them

Utilizing angular's cookie library, I have successfully set a cookie to store the id and passcode of a shopping cart on the backend. However, despite setting the expiration date to a past time in order to expire the cookie once the cart is purchased, ...

How can I prevent clearQueue() from removing future queues?

In my code, I have a button that triggers the showing of a div in 500ms when clicked. After the div is shown, a shake class is added to it after another 500ms. The shake class is then removed after 2 seconds using the delay function. However, if the user c ...

Container that displays vertical scroll while permitting floating overflows

Is there a way to set up a container so that when the window size is too small, it displays a scroll bar to view all elements that don't fit in one go? At the same time, can the child containing floating elements be allowed to extend beyond the bounda ...

Converting an object to JSON in javascript: A step-by-step guide

I have been attempting to convert my object person into a JSON format. const person = new Object(); person.firstName = 'testFirstName'; person.lastName = 'testLastName'; var myJson = JSON.stringify(person); ...

Handling errors within classes in JavaScript/TypeScript

Imagine having an interface structured as follows: class Something { constructor(things) { if (things) { doSomething(); } else return { errorCode: 1 } } } Does this code appear to be correct? When using TypeScript, I en ...

PhantomJS fails to trigger function within page.evaluate

My current project involves scraping data from a Facebook page using the PhantomJS node module (https://github.com/sgentle/phantomjs-node). However, I am facing an issue where the function I pass to evaluate the page is not being executed. Interestingly, w ...

Vuetify's v-data-table is experiencing issues with displaying :headers and :items

I'm facing an issue while working on a Vue project with typescript. The v-data-table component in my Schedule.vue file is not rendering as expected. Instead, all I can see is the image below: https://i.sstatic.net/AvjwA.png Despite searching extensi ...

find all occurrences except for the last of a pattern in javascript

When considering the patterns below: "profile[foreclosure_defenses_attributes][0][some_text]" "something[something_else_attributes][0][hello_attributes][0][other_stuff]" It is possible to extract the last part by utilizing non-capturing groups: var rege ...

Exploring the method to retrieve data on the server side through Express when it is shared by the client within a put request

Here is the angular http put request I am working with: sendPutRequest(data) : Observable<any>{ return this.http.put("http://localhost:5050", data).pipe(map(this.handleData)); } After making this call, the server side method being invoked is ...

Is it possible to track when a user switches to a different component in Angular?

I'm looking to set up a confirmation popup when the user attempts to navigate to a different page. I've come across information about hostListener and canActivate, but I'm not exactly sure how to begin! Any guidance would be greatly apprecia ...

Running the nextjs dev server with configuration settings inherited from a different project

Currently, I am working on a Next.js application. I have a folder named landing/pages/ inside the root folder, and I want to run the development server with those pages by using next dev ./landing. The idea is to create a separate app using the same codeba ...

When attempting to showcase array information in React, there seems to be an issue with the output

After printing console.log(response.data), the following output is displayed in the console. https://i.sstatic.net/LLmDG.png A hook was created as follows: const [result,setResult] = useState([]); The API output was then assigned to the hook with: setRe ...

Ways to incorporate sass:math into your vue.config.js file

While using vue-cli with Vue 2.6 and sass 1.49, I encountered errors in the console related to simple division calculations: Deprecation Warning: Using / for division outside of calc() is deprecated and will be removed in Dart Sass 2.0.0. I attempted to ...

The issue of the Ajax beforeSend function not triggering at times, causing a delay in displaying the bootstrap progress

I'm experiencing issues with my Bootstrap tabs and the progress bar not consistently showing up. I have 3 tabs, each displaying query results in a table. Whenever the search button is clicked or a tab is changed, an ajax call triggers a function with ...

Is there a way to verify if the meteor.call function was executed successfully?

In my meteor/react application, I am working with two components. I need to pass a method from one component to the other: saveNewUsername(newUsername) { Meteor.call('setNewUsername', newUsername, (error) => { if(error) { ...

What strategies can be utilized to raise the max-height from the bottom to the top?

I am facing the following coding challenge: <div id = "parent"> <div id = "button"></div> </div> There is also a dynamically generated <div id="list"></div> I have successfully implem ...

Issue with Vue 2: Promise does not resolve after redirecting to another page

Although I realize this question might seem like a repetition, I have been tirelessly seeking a solution without success. The issue I am facing involves a method that resolves a promise only after the window has fully loaded. Subsequently, in my mounted h ...

The functionality of changing the checkbox to "checked" by clicking on the span is not

How can I create a toggle button with a checkbox using css and jquery? Clicking on the span representing the toggle button should change the checked property of the checkbox. Currently, the span does not change the property, even though it triggers the c ...

The video player will only start playing after the source has been changed if it was already in play

I am facing an issue with my video player that has thumbnails. The problem is that the video player does not start playing the selected video unless the video is already playing. This means I have to hit the play button first, and then select the thumbnail ...

What is the reason behind using <script> tag for scripts, instead of using <style> tag for external CSS files?

A family member who is new to Web Development posed an interesting question to me. Why do we use <script src="min.js"></script> and <link rel="stylesheet" href="min.css">? Why not simply use <style href="min.css"></style>? Wh ...