javascript - 在 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
在控制台中返回我一个对象,没有别的
解决方案
尝试 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);
})
推荐阅读
- java - 从多命名空间 XML 中删除命名空间的数据
- docker - 自动从 php fpm 镜像启动 Nginx
- matlab - MATLAB 表 - 选择满足条件的第一行
- windows - 在 Get cmdlet 中过滤掉空参数值
- mongodb - 无法从远程服务器导出 MongoDB 数据库
- symfony - 如何将 Bootstrap 添加到我的 Symfony 4.1 项目中?
- ios - iOS 中 ARKit 1.0 中的持久性 AR 数据
- ms-word - OpenXML / Xceed插入没有空行的表
- java - IntelliJ 中 gradle 插件的信任库设置
- python - altair 中的重复图