【问题标题】:Using RxJS ForkJoin to combine results from multiple API calls使用 RxJS ForkJoin 组合多个 API 调用的结果
【发布时间】:2020-12-04 22:38:54
【问题描述】:

我正在尝试使用 RxJS forkJoin 来组合 2 个 api 调用(理想情况下,我会及时添加更多)。我正在使用 RxJs 6。

我有两个接口。一个接口IMyWrapperObj,持有另一个接口IData的数组。

export interface IMyWrapperObj {
  status: {
    id: number;
    prop: string;
    anotherProp: string;
  }
 data: Data[]
}

export interface IData {
   prop1: string;
   prop 2: string;
}

我有一个调用第三方 api 的服务。这个API的设置方式,我需要用不同的参数调用两次,然后在Angular端合并结果。

getSomeDataFromAPI(param1, param2): Observable<IMyWrapperObj> {/// some code here}

现在,在组件中,我已将服务注入到构造函数中,在 ngOnInit 中,我打算使用 forkJoin 进行 2 次 api 调用并将输出合并为一个结果。

代码如下:

forkJoin({
   request1: this.dataService.getSomeDataFromAPI('Astronomy', this.query.term),
   request2: this.dataService.getSomeDataFromAPI('History', this.query.term)
}).subscribe(val => console.log(val));

我无法解决的错误(编译时)是:

Observable 不可分配给 ObservableInput 类型。从字面上看,对象是我唯一指定的已知属性。

对此有什么想法吗?我一直无法消化一个明确的答案。

【问题讨论】:

  • 您使用的是哪个版本的 RxJS?旧版本不支持您在此处使用的字典语法。我认为在 6.5 版本之前不支持这种语法
  • 还有你的服务有哪些?
  • getSomeDataFromAPI 返回一个属性未全部定义的类型吗?你能显示你的getSomeDataFromAPI 电话吗?

标签: angular rxjs


【解决方案1】:

基于 forkJoin 的文档

我觉得订阅fork join的方式有问题

forkJoin({
   request1: this.dataService.getSomeDataFromAPI('Astronomy', this.query.term),
   request2: this.dataService.getSomeDataFromAPI('History', this.query.term)
}).subscribe(({request1,request2}) => {
console.log(request1);
console.log(request2);
});

我使用 forkjoin 的常用方法是使用数组及其索引

service.ts:-

   getSomeDataFromAPI(Requests:Array<any>): Any {
    //create a request observable batch array
    let observableBatch = [];
    //inside the array push each http request observable
    Requests.forEach((request)=>{
    observableBatch.push(         
                    //service call
                    this._http
                    .post<IMyWrapperObj>(Url, { 
            requestbodyParam1: request.param1,
            requestbodyParam2: request.param2
                })
                    .pipe(
                        //catcherror block http
                    )
    
                ); //push end
    
         });
   //use forkJoin 
 return forkJoin(observableBatch);

    }

component.ts:-

//使用foreach或map或任何方式重写下面的代码或根据需要使用接口包装器

    let requests:Array<any>=[{'Astronomy', this.query.term},{'History', this.query.term}];
    


this.dataService.getSomeDataFromAPI(requests:Array)
                .susbcribe((response:Any[])=>{
     console.log(response[0]);//astronomy response
     console.log(response[1]); //history response
         
                 },{error}=>{
                 //error block
               });

https://www.learnrxjs.io/learn-rxjs/operators/combination/forkjoin

【讨论】:

    猜你喜欢
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 2018-08-15
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多