问题描述
我有一个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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!