我有一个参数列表,对于每个参数,都会向服务器发送一个请求。参数的数量可能会有所不同,因此请求会循环发送。问题是,如何发送所有参数的请求,等待所有请求的响应并继续执行程序。为此,您需要使用 RxJS。
private getValuesForEditTariff(parameter: Parameter) {
if (parameter.dependParams != null && parameter.dependParams.length > 0) {
let pars: Parameter[] = new Array<Parameter>();
this.actionEditTariff.groups.forEach(group => {
pars = pars.concat(group.parameters);
});
let locator = (p: Parameter, id: number) => p.id == id;
let service = this.actionService;
let action = this.actionEditTariff;
parameter.dependParams.forEach(parameter => {
let par = pars.find(p => locator(p, parameter));
if (par) {
par.loading = true;
service.getValues(parameter, pars,action.action, action.actionScheme).subscribe({
next: (data) => {
par.values = data;
par.loading = false;
console.log("Значения получены");
},
error: (error)=> {
this.message = error.error.message || error.statusText;
par.loading = false;
this.showError();
}
})
}
})
}
}
我尝试使用 concatMap,但我不知道它是如何工作的
您可以使用forkJoin来等待所有的回复,就像这样
private getValuesForEditTariff(parameter: Parameter) {
if (parameter.dependParams != null && parameter.dependParams.length > 0) {
let pars: Parameter[] = new Array<Parameter>();
this.actionEditTariff.groups.forEach(group => {
pars = pars.concat(group.parameters);
});
const locator = (p: Parameter, id: number) => p.id == id;
const service = this.actionService;
const action = this.actionEditTariff;
const parameters$ = parameter.dependParams.reduce((parameters, parameter) => {
const par = pars.find(p => locator(p, parameter));
if (par) {
par.loading = true;
parameters.push(
service.getValues(parameter, pars, action.action, action.actionScheme).pipe(
tap(() => {
par.values = data;
par.loading = false;
console.log('Значения получены');
}),
catchError(() => {
this.message = error.error.message || error.statusText;
par.loading = false;
this.showError();
return of(null);
}),
),
);
}
return parameters;
});
forkJoin(parameters$).subscribe();
}
}