在ngOnInit函数中将两个json合并为一个json

编程入门 行业动态 更新时间:2024-10-28 10:24:05
本文介绍了在ngOnInit函数中将两个json合并为一个json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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 looked at some other threads and found that Object.assign can be used for this purpose but the problem is that i am adding data to objects inside the subscriber function and Object.assign is outside the subscriber function so objects are undefined outside the subscriber function. Here is my code

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 向我返回了控制台中的一个对象,除此之外没有其他

CompleteData is returning me an object in console and nothing else

推荐答案

我认为您可以使用Promise

I think you can use Promise

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); }); }

更多推荐

在ngOnInit函数中将两个json合并为一个json

本文发布于:2023-10-19 14:24:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1507788.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:并为   中将   函数   两个   ngOnInit

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!