首页 > 解决方案 > 在 ngOnInit 函数中将两个 json 合并为一个 json

问题描述

我有一个 Angular 组件,它在加载调用 2 个服务方法和这些方法作为回报时,以 json 格式返回数据。我想将这两个 json 合并在一起。我确实查看了其他一些线程,发现Object.assign可以用于此目的,但问题是我正在向订阅者函数内部的对象添加数据并且在订阅者函数Object.assign之外,因此对象在订阅者函数之外未定义。这是我的代码

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在控制台中返回我一个对象,没有别的

标签: javascriptjsonangulartypescript

解决方案


尝试 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


推荐阅读