Search code examples
angulartypescripthttpservice

How to call service with in for each?


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"); }

When service is called instead of executing the HTTP call first it calls the method in inside service. Not sure what to do?

using 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;
            }
        })
    }

What's wrong with this? I'm using forkjoin its not working as expected


Solution

  • @Sanjana, the "key" of forkjoin is "join" observables, so "trying" should return an observable

      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))
      }