0

I would to have a function which sends an http request to an endpoint giving the list of all items, and then sending a second request to get the first element on that list. The function should return the last item. I'm using the following code but the second http request is not working.

getFirstItem(): Observable<any> {
  return this.getList().pipe(concatMap(value => this.getItem(value[0].id)));
}

Using Angular 7 and rxjs 6.4.0

Any help is appreciated.

Edit: When running the following snippet, the second console log never gets called

getFirstItem(): Observable<any> {
  return this.getList().pipe(
    tap(x => console.log(x)),
    concatMap(value => this.getItem(value[0].id)),
    tap(x => console.log(x)) // never called
}
8

2 Answers 2

1

Your code looks fine. I just wonder how this.getItem is implemented.

Anyway here is an working example with concatMap: https://stackblitz.com/edit/rxjs-api-call-jvqj5q?file=src/app/app.component.ts

You can use mergeMap, concatMap, switchMap. All of them will work. They just behave differently regarding how the inner Observable (this.getItem) is treated when the outer observable emits (this.getList).

More info here: https://morioh.com/p/fcfea9850b90

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

Comments

-1

You can use mergeMap

var result = this.getList().pipe(
  mergeMap(value =>  this.getItem(value[0].id)))
);

2 Comments

I didn't downvote but, I'm trying to understand why its not working, not to use another operator
I think someone punished you for this answer, Your answer is OK but the topic is replicated

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.