Invoke async Method in Angular Typescript

217 Views Asked by At

We are new to angular and we are having few methods needs to be invoked in sequence and return a value. Here the return is invoking before completing the execution. I have tried different things like async await, promise, setTimeout but no luck. Is there any solution to work this in sync order in angular

transform(input:any)
{

    this.getCachedUsers(); // this will set the this.CachedUsers array using a http get call(subscribe)
    this.getUserFromCachedUsers(input); // this will set the this.userName based on input userId from this.CachedUsers
    return this.userName; // here its returning empty
}
1

There are 1 best solutions below

4
Drashti Dobariya On

You should try using observable flat operators.

For transforming items emitted by an Observable into another Observable after completion of the previous observable, you probably want to use the concatMap operator. It creates an inner Observable and flats its result to the outer stream.

const source = this.getCachedUsers()
    .pipe(
        concatMap(result => this.getUserFromCachedUsers(result.userId))
     )
    .subscribe(result2 => {
        // do some stuff
    });

Here are some flat operators you can use that behave differently:

  • flatMap/mergeMap - creates an Observable immediately for any source item, all previous Observables are kept alive

  • concatMap - waits for the previous Observable to complete before
    creating the next one

  • switchMap - for any source item, completes the previous Observable
    and immediately creates the next one

  • exhaustMap - map to inner observable, ignore other values until that observable completes