1

Imagine that I have a service that fetches some posts from the server.

constructor(private api: APIService) {}

So I make a get request like this:

 this.api.getPosts(posts => this.posts = posts);

Now if I want to make a post request I would do this inside the component:

postNew(post) {
    this.api.postNew(post).subscribe(post => this.posts.push(post))
}

My question is the each time I make a post request the above method executes and a new subscriber is created. Which is bad I think. This will occur for other verbs like put, patch and delete. So is there a way around this? I mean to prevent memory leaks.

Do I need to manage subscriptions for each of these methods ? But that will be crazy. Is it ok to pipe a first operator? I'm not sure.

Please suggest a best practice.

atiyar
  • 7,762
  • 6
  • 34
  • 75
mx_code
  • 2,441
  • 1
  • 12
  • 37

1 Answers1

1

If you use the default Angular HttpClient (which I assume) you don't have to worry about those subscriptions. The returned observable will send a complete message to the subscriber after receiving the response data and calling all subscribers. The complete message will automatically unsubscribe all subscribers.

You can check this by providing a complete callback to the subscribe function:

this.http.get("/assets/test.json")
  .subscribe(
    (data)=>console.log(data),
    (error)=>console.log(error),
    ()=>console.log("complete")
  )
David B.
  • 695
  • 5
  • 10