0

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 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the nice explanation. In my case the returning is the problem. first method is observable and the second method is sync method. If I do with with observable, the first two methods can be inside the pipe and map but the return still executes before the previous operation completed. @drashti-dobariya
Rather than returning a variable, you can return observable with the the value of userName. Then wherever you want to use it, you can directly subscribe to that observable.
Also, if you are using a class variable, you wont need to return it.
since this is a pipe transform method, we are returning since this value will be using in the consuming end. I will try with subscribe and return in same method.

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.