简体   繁体   English

角度5 HttpClient可观察的重用

[英]angular 5 HttpClient observable reuse

i create a service returning user details from server using the HttpClient.get. 我创建了一个服务,使用HttpClient.get从服务器返回用户详细信息。

public getUser(id: number): Observable<User>{

return this.http
  .get<User>('myUrl?id='+id);}

i have injected the service into a component. 我已经将服务注入组件。 in the component i would like to get a user so i have subscribed to the service method wich is returning Observable. 在组件中,我希望获得一个用户,因此我已经订阅了返回“ Observable”的服务方法。

so far so good. 到现在为止还挺好。

my problam: now i would like to get another user and the question is how i activate the service method to get the user again ?? 我的问题:现在我想获得另一个用户,问题是我如何激活服​​务方法以再次获得该用户?

should i unsubscribe and subscribe again every time i need a user ? 每当需要用户时,我应该取消订阅并再次订阅吗?

All Observables returned from HttpClient are cold . HttpClient返回的所有Observable都是冷的

Observables are functions that tie an observer to a producer. 可观察变量是将观察者与生产者联系起来的函数。 An observable is “cold” if its underlying producer is created and activated during subscription. 如果可观察对象的基础生产者在订阅期间创建并激活,则它是“冷”的。 This means, that if observables are functions, then the producer is created and activated by calling that function. 这意味着,如果可观察变量是函数,则通过调用该函数来创建和激活生产者。 ( source ) 来源

so, it's fine to subscribe to your service HttpClient method multiple time and call it from different places, and you don't need to unsubscribe from it. 因此,多次订阅您的服务HttpClient方法并从不同位置调用它是很好的,您无需取消订阅。 But please keep it in mind it's neccesery to unsubscribe all your subscribers on component destroy. 但是请记住,取消组件销毁的所有订阅者都是必要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM