【问题标题】:How to call service with in for each?如何为每个调用服务?
【发布时间】:2021-05-24 15:42:05
【问题描述】:
private Payload(): asset { 
    const payload = { //pay load }
    return payload; 
}
  
public listofnumbers() { 
    number = [1,2,3]; 
    number.forEach(element => { 
        this.service(element); 
    }); 
}
 
private service(number) {
    this.service.getNumbers(this.Payload())
        .subscribe((res) => { 
            if (res.isSuccess && res.data) { 
                this.function(); 
            } 
        }) 
} 

function () { alert("fghj"); }

当调用服务而不是首先执行 HTTP 调用时,它会调用服务内部的方法。 不知道该怎么办?

使用forkjoin

 public sendSelectedToD365() {
    let assetDetails1 = [];
      let assetSearchValue =(this.searchAssetForm.controls['assetSearch'].value).split(',');
      let mycalls = assetSearchValue.map(x => this.trying(x))
      forkJoin(mycalls).subscribe(res => {
        console.log(res)

      })
    }

  private trying(x)
      {     this.assetService.getAssetDetails(this.AssetDetailsPayload(x)).subscribe((res) => {
            if (res.isSuccess && res.data) {
              return res.data;
            }
        })
    }

这有什么问题?我正在使用 forkjoin 它没有按预期工作

【问题讨论】:

  • 先在服务内部调用什么方法,在里面看不到HTTP调用
  • 这能回答你的问题吗? Call Angular service inside forEach loop
  • 我试图让它成为一个承诺,但它并没有像例外那样工作。
  • 不,这对@R.Richards 没有帮助
  • 谁能告诉我如何用例子编写代码,我对 angular 很陌生。

标签: angular typescript http service


【解决方案1】:

@Sanjana,forkjoin 的“关键”是“加入”可观察对象,因此“尝试”应该返回一个可观察对象

  public sendSelectedToD365() {
      let assetDetails1 = [];
      let assetSearchValue =(this.searchAssetForm.controls['assetSearch'].value).split(',');
      let mycalls = assetSearchValue.map(x => this.trying(x))
      forkJoin(mycalls).subscribe(res:any[] => {
        console.log(res)
        // in res[0] you has the response to the first call
        // in res[1] you has the response to the second one
        // ...
        res.forEach((x,index)=>{
          console.log("The response to",assetSearchValue[index],"is ",res[index])
        })

      })
    }

  private trying(x):Observable<any>
  {         
       //see that you use return the Observable
         return this.assetService.getAssetDetails(this.AssetDetailsPayload(x))
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 2019-11-16
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多