Jan Krüger
Jan Krüger

Reputation: 83

TypeScript foreach() with async http request

I have an Issue with my angular webapp. I am trying to iterate over an array and make each time a HTTP request to obtain the ID to the Module, which is an Object:

{name:string, charge:string}

Once I have updated every Module with the new property id, I want to do some stuff with these IDs. For that I need all the IDs and cannot process each Module individually. How do I achieve that? I know, because the http.get() function within Angular is async I cannot simply paste my code after the foreach() loop.

Here is my code:

ngOnInit() {
let fit = parseFit(megafit.default.fit);
fit.modules.forEach(Module => {
  this.http.get(`https://esi.tech.ccp.is/v2/search/?categories=inventory_type&search=${Module.name}&strict=true`)
  .subscribe((data:any) => {
    Module.id = data.inventory_type
  })
});
// Do something with all the IDs 

}

Upvotes: 1

Views: 1266

Answers (2)

A.Winnen
A.Winnen

Reputation: 1698

You'll need some RxJS Operators to to this.

Use from to make Module[] to Observable<Module> then Pipe the stream into mergeMap and perform the api request. Use tap to alter your module Object with the result from API and at last use toArray to collect the responses. Subscribe to the stream to do the action you'll want to to when all modules are processed.

example:

from(fit.modules).pipe(
    mergeMap(module => this.http.get(...).pipe(
        tap(apiResponse => module.id = apiResponse.inventory_type)
    )),
    toArray()
).subscribe(allResponses => {
    // do your action
});

Upvotes: 1

Gabriel Lopez
Gabriel Lopez

Reputation: 452

Use promises instead of subscribers

ngOnInit() {
let fit = parseFit(megafit.default.fit);
const jarOfPromises =[];
fit.modules.forEach(Module => {
jarOfPromises.push(
  this.http.get(`https://esi.tech.ccp.is/v2/search/?categories=inventory_type&search=${Module.name}&strict=true`)
  .toPromise())
});

Promise.all(jarOfPromises).then(results=>{
/** your code **/
});

Be advised I wrote this in my cell phone 🤓

Upvotes: 0

Related Questions