TransWikia.com

Wait for observable to get array-data

Stack Overflow Asked by bena on December 25, 2021

I know there have been several questions regarding this, but I havent found a way that works for me properly. If you find one gladly send it to me.

So I am getting my data from an API and I convert this data into an array of my required datatype:

getData(): Observable<Type[]> {
    return this.http.get<Type[]>("URL)
      .pipe(
        retry(2),
        catchError(this.handleError)
      );
  }

I want to use the data, after I got it.

Some ways i tried to solve this were with while(empty){...} which seems to be unefficient and not correct if the array is empty, Promises where I didn’t really find a way to connect properly with observables and await/async which seems to be impossible with observables.

My code of implementing this:

array: Type[] = [];
useJSON(searchString: string) {
    this.configService.getData().subscribe(results => { this.array = results});
    // --operations--
  }

2 Answers

I am not exactly sure what you're looking for. If you need to do further operations after the this.array is initialized, then include them inside the subscription after the assignment.

array: Type[] = [];
useJSON(searchString: string) {
  this.configService.getData().subscribe(results => { 
    this.array = results;
    // --further operations--
  });
}

Answered by Michael D on December 25, 2021

async/away should work for you (syntax might be slightly invalid)

youdMethod() async{
let res=null;

do{
 res=await this.configService.getData().toPromise();
}while(resBasedCondition)
 
}

what you probably wat is to have operator repeatIf but it is not available. Behavior can be mimic using expand as shown here https://stackoverflow.com/a/51644077/1527544

Answered by Antoniossss on December 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP