如何在Angular的另一个HTTP get方法订阅中订阅HTTP get方法?

  • 本文关键字:方法 get HTTP Angular 另一个 angular
  • 更新时间 :
  • 英文 :


在Angular中,我需要从子订阅中更新父订阅中的数据。下面是示例代码供您参考。你能帮我解决这个问题吗?

this.httpClientService.get('access/Details?Id=' + Id + '')
.subscribe((data: Any[]) => {           
data.forEach((dt, i) => {
dt.resource.forEach((rr, j) => {
if (rr.approval.empId != null) {
this.httpClientService.get('employee/get?id=' + rr.approval.empId + '')
.subscribe((e: Employee) => {
data[i].resourceRoles[j].approval.Name = e.lastName + "," + e.firstName;
})
}
})
})          
})

数据在所有操作完成后更新。无法在循环中更新。

Thanks in advance…

您正在运行异步操作,因此需要等待所有请求完成后才能使用已修改的数据。您可以使用EventEmitter来通知主进程所有请求的完成。

import { Component, OnInit, EventEmitter } from '@angular/core';
@Component({
// ...
})
export class YourComponent implements OnInit {
// ...
modifiedData: any[];
notifier = new EventEmitter<any>();
constructor(
// ...
){}
ngOnInit() {
this.notifier.subscribe((value) => {
// all data items have been modified, do what you want
});
}
// your data retrieval function
getData() {
this.httpClientService
.get('access/Details?Id=' + Id + '')
.subscribe((data: any[]) => { 
let requestQty = 0;
let completedRequestQty = 0;
this.modifiedData = data.slice(); // make a copy of the data

data.forEach((dt, i) => {
dt.resource.forEach((rr, j) => {
if (rr.approval.empId != null) {
requestQty++; // increment number of requests
this.httpClientService
.get('employee/get?id=' + rr.approval.empId + '')
.subscribe((e: Employee) => {
this.modifiedData[i].resourceRoles[j].approval.Name = e.lastName + "," + e.firstName;
completedRequestQty++; // increment number of completed requests
if (requestQty === completedRequestQty) { // all requests have been completed
this.notifier.emit(true);
}
})
}
})
})

// if no request
if (requestQty === 0) { 
this.notifier.emit(true);
}

})
}
}

最新更新