0

I have created an Angular application which allows users to comment on a particular media file (like video). When a comment is posted, it makes a http POST call which stores the comment in the database.

While loading the component, ngOnInit loads all the comments from the database by making a http GET call. But, the comments doesn't get updated without refreshing the page when a new comment is posted. Is their a way to update the comments list without refreshing the page when a comment is posted?

2 Answers 2

2

subscribe your http.post and when success posting add the post to your array of posts this.posts.push(newPost)

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

Comments

0

For simplicity let's say you have one component ViewComponent, that shows the list of comments as well as the comment form to add a new comment. The ViewComponent has a local state of the comments like public comments: Comment[], which gets initialized by the GET api call in your ngOnInit().

I'm assuming you have a service like CommentsService that makes the api calls. When you add a comment, the function addComment(comment) is called, which handles the POST request. When the POST was successful, the comment is added to your comments array.

If the service returns an Observable (here without unsubscribe):

addComment(comment: Comment): void {
  this.commentService.add(comment)
    .subscribe(comment => {
      this.comments.push(comment);
    });
}

If the service returns a Promise:

addComment(comment: Comment): void {
  this.commentService.add(comment)
    .then(comment => {
      this.comments.push(comment);
    });
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.