I have a service that makes some http call to a rest api. On my component I have a subscribe to it. How can I update the data on the subscribe without having to make a new call to the service?
问题:
回答1:
The question is not quite clear, but I think I can infer enough to hopefully offer an answer.
Let's assume you have an observable of a User
object that has an OrganizationId
property on it, and you want an observable of the Organization
object associated with that OrganizationId
. You want it to update when the user updates, right?
This is what you would want to use the flatMap
operator for. Assume our organizationService
has a byId$
method that takes in the OrganizationId
and returns an observable from the http.post()
method.
organization$ = user$
.flatMap(user => organizationService.byId$(user.OrganizationId));
You can think of flatMap
as similar to map
in that it will take one value, and turn it into another based on the callback that you pass to it. The difference is that if you used the normal map
in this way, you would end up with an observable of an observable. flatMap
will unwrap the observable that is returned to it so you just have an observable of your desired object.