0

I created a service returning user details from server using the 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 which is returning Observable<user>.

so far so good.

my problem:
Now I would like to get another user and the question is how do I activate the service method to get the user again?

Should I unsubscribe and subscribe again every time I need a user?

1
  • Observable returned by httpClient methods are cold and completes just after the response. So you don't have to unsubscribe ( cause the Observable complete after the response ). And yes you have to call again getUser(<id>) and subscribe to the new observable returned Commented Jan 24, 2018 at 8:27

1 Answer 1

2

All Observables returned from HttpClient are cold.

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. But please keep it in mind it's neccesery to unsubscribe all your subscribers on component destroy.

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

Comments

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.