如何更新我的订阅数据? [英] How can I update my subscribe data?
问题描述
我有一项服务,可以对rest api进行一些http调用.在我的组件上,我有一个订阅.如何在不重新调用服务的情况下更新订阅上的数据?
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?
推荐答案
这个问题不是很清楚,但是我认为我可以推断出希望提供答案的原因.
The question is not quite clear, but I think I can infer enough to hopefully offer an answer.
让我们假设您有一个具有OrganizationId
属性的User
对象的可观察对象,并且您想要与该OrganizationId
关联的Organization
对象的可观察对象.您希望它在用户更新时更新,对吗?
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?
这就是您要使用flatMap
运算符的目的.假设我们的organizationService
有一个byId$
方法,该方法接受OrganizationId
并从http.post()
方法返回一个可观察值.
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));
您可以认为flatMap
与map
相似,因为它将使用一个值,并根据传递给它的回调将其转换为另一个值.区别在于,如果您以这种方式使用普通的map
,则最终会得到一个可观察的对象. flatMap
将解开返回给它的可观察对象,因此您只需拥有所需对象的可观察对象即可.
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.
这篇关于如何更新我的订阅数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!