首页 > 解决方案 > 订阅多个异步 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);
            }
        });
} 

标签: angulartypescriptrxjs

解决方案


您可以使用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);
       });                                                          
}

推荐阅读