RxJS: Accessing a previous value further down the pipe chain
Often we want to access a value from a previous operator in RxJS, but that value is no longer available. Let me illustrate the problem with an example: We have a users email in our code From the email we want to get a user object We then want to find all the products that this user has shown interest for We then want to see if our user is a premium member, if so we want to return the products with discounted prices getUser(email).pipe( mergeMap(user => getProducts(user.interests)), map(products => { // The line below will fail, the user is undefined if (user.isPremiumMember) { return discountPrices(products); } else { return products; } }) ); As you can see above, we want to access the user object both in the “mergeMap” and in the following “map”. But the user object is no longer available in the “map”. So what can we do? I will present 4 solutions to this problem Solution 1 and 2 will behave a bit d ifferently from solution 3 and 4. ...