Combine two JSON objects into a single JSON object within the ngOnInit function

I am dealing with an Angular component where, upon loading, two service methods are called to fetch data in JSON format. My goal is to merge these two sets of data together. After researching other solutions, I discovered that Object.assign could accomplish this task. However, I encountered an issue - since I am adding data to objects within the subscriber function, the objects are undefined outside of it. Below is my code snippet:

export class UpcomingClassesComponent implements OnInit {

  times: ClassTimes = new ClassTimes();
  schedule: ClassSchedule = new ClassSchedule();
    classes: any; 
    timing: any;
    data: any;

  constructor(private router:Router,
              private _classService: ClassServiceProxy) {

  }

  ngOnInit() {
    this._classService.GetClassData()
    .subscribe((result: any) => {
      this.schedule = result;
      this.classes = this.schedule;
      //console.log(this.classes);
    })

    this._classService.GetClassTimes()
    .subscribe((data: any) => {
      this.times = data;
      this.timing = this.times;
      //console.log(this.timing);
    })

    let completeData = Object.assign({}, this.classes, this.timing);
    console.log(completeData); 

    }

CompleteData is returning only an object in the console and nothing else.

Answer №1

Give forkJoin a try

 forkJoin([_courseService.getCourseDetails(),_courseService.getCourseInfo()
  ]).subscribe((result: any[]) => {

    this.data = result[0];
    this.courseDetails = this.data;

    this.info = result[1];
    this.courseInfo = this.info;

   let completeCourseData = {...this.courseDetails, ...this.courseInfo};
   console.log(completeCourseData);
  })

Check out the StackBlitz demo

Answer №2

Using a Promise can help in this situation

ngOnInit() {
  let dataPromise = new Promise((resolve) => {
    this._classService.GetClassData()
    .subscribe((result: any) => {
      resolve(result[0]);
    })
  });

  let timesPromise = new Promise((resolve) => {
    this._classService.GetClassTimes()
    .subscribe((result: any) => {
      resolve(result[0]);
    })
  });

  Promise.all([dataPromise, timesPromise])
  .then((values) => {
    console.log(values);
    let completeData = { ...values[0], ...values[1]};
    // let completeData = Object.assign({}, values[0], values[1]);
    console.log("final results : ", completeData); 
  });
}

Answer №3

Give this a shot:

this._classService.FetchClassTimes()
    .subscribe((response: any) => {
      this.times = response;
      this.timing = this.times;
      this._classService.LoadClassData()
      .subscribe((data: any) => {
      this.schedule = data;
      this.classes = this.schedule;
})
      this.collectAllData();
    })

collectAllData() {
let allData = { ...this.classes, ...this.timing};
    console.log(allData);
}

Answer №4

Utilizing ForkJoin is a more effective strategy, however, it is recommended to avoid using indexes in its subscription. A preferable method would involve utilizing tap where the Object is assigned as they resolve. This eliminates the need for manual indexing of results and aids in maintaining scalability.

forkJoin([
  classes.pipe(tap(res => {
    Object.assign(completeData, res)
  })),
  timing.pipe(tap(res => {
    Object.assign(completeData, res)
  }))
]).subscribe(_ => {
  //carry out further actions
  console.log(completeData)
})

Check out the Stackblitz demo at https://stackblitz.com/edit/angular-forkjoin-with-tap

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

Exploring the Relationship Between CSS Attribute Values and Strings in Eclipse

Looking to conduct a test to determine whether the value of a CSS attribute matches a specific string. The comparison functions correctly in JSFiddle, providing the expected result. However, Eclipse presents a different outcome and appears to interpret the ...

Encountering issues while trying to execute npm and node commands within Visual Studio Code

When I attempt to execute node commands in a command window, such as ng serve -o, everything works fine. However, when I try to do the same in VS Code, I encounter the following error message: ng : The term 'ng' is not recognized as the name of ...

When I leave an input empty in JSX, my 'required' attribute does not work properly

Currently, I am working on a register.jsx file, but I am encountering an issue where clicking the button still triggers functionality even when the input fields are empty or undefined. I have reviewed my code multiple times and cannot identify any syntax ...

If a second instance is hidden, SVG will appear as a mysterious black box

Two separate div elements each contain an identical SVG graphic. If I hide the first div by setting it to "display: none", the SVG in the second div appears as a gray box. This issue is present in both Firefox and Chrome browsers. Any insights into why ...

Having difficulties with Vue components displaying in Laravel's blade.php file

Let me share my current setup with you: This is the main "Welcome.blade.php" file where I have included relevant information as the file is quite lengthy: <div id='app'> <router-view></router-view> </div> <script src ...

Having difficulty parsing the JSON using the JSON Framework

Below is the json data that I have: { "response": { "status": 200 }, "user": { "flex_meta": { "layout": "[{\"windows\":[{\"type\":\"stream\",\"width\":260,\"x\":268 ...

How to return the same value as the input value in Vue before the action is completed

When creating a component and module for functionality X while using Vuex for state management, the code initially works fine. However, after the first insertion, the Getter function consistently returns the previous input value before the action is commit ...

Creating a visual representation from an array of strings to produce a

My goal is to organize a list of server names into a map using a specific logic. For instance, with names like: "temp-a-name1", "temp-a-name2", "temp-b-name1", "temp-b-name2" They would be mapped as: { a: [ "temp-a-name1", "temp-a-name2" ] ...

Expanding the size of select dropdown in Material UI to accommodate more options

Is there a way to increase the width of the drop down to 400px? I tried adding inline styles, but it didn't work. Upon debugging, I realized that the width is being overridden by this class. I'm not sure how to overwrite it. Could you please prov ...

Using Vuejs to implement pagination on a weekly basis

I need some help with Vue pagination. I have a ticket object, and currently, it displays in a certain way. What I'm trying to achieve is to display the tickets weekly. For example, if this week is the 31st week of the year, then from today until Sunda ...

Learn how to manipulate data within a MongoDB database schema using Node.js and Mongoose: inserting, saving, and updating records

When inserting data into the MongoDB schema presented below, make sure that Employee name, Project name, and client name can be the same, but the employee ID must be unique. Duplicate entries are not allowed. var StatusSchema = new mongoose.Schema({ ...

The functionality of displaying a loading image when the Upload button is clicked has encountered a glitch and

I am looking to add a feature that displays a loader when a user uploads a file by clicking on a button. The loader should be visible while the data is being processed in the background. To achieve this, I have included a div as shown below: <div id=" ...

Why is it that Object.getOwnPropertyDescriptors does not function on HTMLElements?

Upon traversing the prototype chain, one would expect to find Object.prototype at the bottom (or top?), leading to the assumption that they would function like typical objects. However, when using Object.getOwnPropertyDescriptors, the properties obtained d ...

Using Vue to store form elements inside a component and accessing the data

Can someone help me decide if my approach makes sense? I may have gone overboard with components and now I'm questioning the benefits. I've created separate components for both the input field and send button in a form, but I'm facing challe ...

Auto-suggest dropdown menu with pre-populated options

I am looking to implement a feature where users can click on an icon and a dropdown menu will appear, allowing them to search through data. To better illustrate this concept, here is an image: Users will be able to input their quiz names in the first sect ...

Searching through Rails active record using a JSONB column

In my database, there is a record called User with a column named attrs. The data in the attrs column is stored as jsonb and it looks like this: I am submitting the JSON representation of a User using as_json: { "id"=>uuid1, "profile_id"=>uuid ...

the event listener for xmlhttprequest on load is not functioning as expected

I am facing an issue with validating a form using JavaScript and XMLHttpRequest. The onload function is supposed to display an alert, but it only works sometimes. I'm struggling to identify my mistake. document.getElementById("button").addEventListen ...

Saving JSON Information in a Flat File or Database

Currently, I am retrieving JSON data from the internet and finding myself unsure about the most efficient storage and retrieval methods for this data. Given that my queries are not particularly complex, would it be better to store the data in a flat file s ...

What is the best way to implement a third-party library that utilizes an outdated import method in Angular 4.x?

Can anyone guide me on how to include the mathjs library in Angular 4.0 and use it within a component? Here are the steps I've taken so far: yarn add mathjs I believe there should be a method for injecting JS libraries during one of the build lifec ...

What could be causing the failure of opening a link within an asynchronous handler on iPad Safari?

Have you ever encountered some unusual behavior when programmatically opening a _blank link? It's happening to me and I'm not quite sure why. Context: Device: iPad 14 Browser: Safari latest I have a button that triggers an async await operatio ...