1

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 

}

2 Answers 2

1

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
});
Sign up to request clarification or add additional context in comments.

Comments

0

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 🤓

2 Comments

why should OP use promises instead of observables?
It’s just a way of achieving what he/she is asking for. In this case I think it is easier to use promises instead of more complex RXJS operators

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.