angular - 订阅多个异步 http 调用
问题描述
在 ngOnInit 上,我对数据发出 4 个 http 请求,之后我需要从服务器加载数据以根据最后 4 个 http 调用的数据模型用数据填充表单。
简而言之,我需要订阅这 4 个 http 调用,如果它们没有失败,请确保它们不会失败,最后我可以调用第 5 个 http 调用以从服务器获取数据。
据我了解,我应该避免使用可观察对象并使用开关,但是如何使用 4 个 http 调用来做到这一点?我应该为 http 调用创建一个可观察的等待,如果在第 5 个 http 调用上成功使用 switchmap?
这是代码。
ngOnInit() {
this.service.getProvince().subscribe(
(value) => { return value; },
(error: AppError) => {
if (error instanceof NotFoundError) {
console.log('Error richiesta http');
} else {
console.log(error);
}
});
this.service.getLingueStraniere().subscribe(
(value) => { return value; },
(error: AppError) => {
if (error instanceof NotFoundError) {
console.log('Error richiesta http');
} else {
console.log(error);
}
});
this.service.getTitoliPreferenziali().subscribe(
(value) => { return value; },
(error: AppError) => {
if (error instanceof NotFoundError) {
console.log('Error richiesta http');
} else {
console.log(error);
}
});
this.service.getRiserve().subscribe(
(value) => { return value; },
(error: AppError) => {
if (error instanceof NotFoundError) {
console.log('Error richiesta http');
} else {
console.log(error);
}
});
}
// this is the 5th call that need to be done only if last 4 call not fail
finalCall {
this.service.getDomanda().subscribe((domanda: any) => {
this.popolaForm(domanda); // Method that use data to fill foms
},
(error: AppError) => {
if (error instanceof NotFoundError) {
console.log('Error richiesta http');
} else {
console.log(error);
}
});
}
解决方案
您可以使用forkJoin
组合所有请求并在所有请求完成时将结果作为回调。
import { forkJoin } from 'rxjs';
import { switchMap } from 'rxjs/operators';
ngOnInit() {
forkJoin([this.service.getProvince(),this.service.getLingueStraniere(),this.service.getTitoliPreferenziali(), this.service.getRiserve()])
.pipe(switchMap(result => {
console.log('Province', result[0]);
console.log('LingueStraniere', result[1]);
console.log('TitoliPreferenziali', result[2]);
console.log('Riserve', result[3]);
return this.service.getDomanda();
}))
.subscribe((domanda: any) => {
console.log('getDomanda', domanda);
});
}
推荐阅读
- ssl-certificate - 使用 cloudflare 及其托管在 infinity free(免费帐户)上的 ssl 证书托管我的网站时出现问题
- gitlab - 当我想更改分支时出现 Git Erro
- http - 更好地使用 URLSession 实时下载连续的 HTTP-Multipart 流
- c# - c#在DataReceived内部调用另一个方法时,串行端口读取被锁定
- google-sheets - 在 Google 表格中勾选复选框时自动创建新行
- powershell - 自动将字符串传递给 powershell 用户输入
- vba - CurrentDb.Execute 错误 3061 和 DAO.Recordset 错误
- angular - 打字稿:如果我忽略循环依赖会发生什么
- docker - Docker - 错误:adduser:UID 0 已在使用中
- java - LogstashJsonEventLayoutV1.json - 带有 JSON 值的“消息”元素