Skip to content Skip to sidebar Skip to footer

Merge Two Json Together Into One Json In Ngoninit Function

I have an Angular component that on loading call 2 service methods and those methods in return, return the data back in json format. I want to merge those two jsons together. I did

Solution 1:

try forkJoin

 forkJoin([_classService.GetClassTimes(),_classService.GetClassTimes()
  ]).subscribe((result: any[]) => {

    this.schedule = result[0];
    this.classes = this.schedule;

    this.times = result[1];
    this.timing = this.times;

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

https://stackblitz.com/edit/angular-2tyv93

Solution 2:

I think you can use Promise

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

  let timesPromise = newPromise((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); 
  });
}

Solution 3:

Try this:

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

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

Solution 4:

ForkJoin is a better approach but it is advised to not to use indexes in its subscription. A better approach would be to use tap where we Assign the Object as they resolve. This helps in not manually indexing the results and help maintain scalability.

forkJoin([
  classes.pipe(tap(res => {
    Object.assign(completeData, res)
  })),
  timing.pipe(tap(res => {
    Object.assign(completeData, res)
  }))
]).subscribe(_ => {
  //do your further loginconsole.log(completeData)
})

Stackblitz at https://stackblitz.com/edit/angular-forkjoin-with-tap

Post a Comment for "Merge Two Json Together Into One Json In Ngoninit Function"