Faster reload of components in Angular

Published

I have created two Angular components: one for creating a new post and one for displaying all posts. After I press the button for creating a post I am being redirected to my PostList component, where all my posts are displayed. I used window.location.href, so that the PostList page can reload automatically, so that the new post appears without the need of manually refreshing. The problem is it’s very slow, and it actually requires two refreshes, one when creating the post and one when refreshing the posts list. Is there a faster way to navigate to the post list and display the new post without manually refreshing the page? If I’m using router.navigateByUrl('/posts') I must manually refresh the page so that the new post appears, which is not desired.

  model: any = {};
  @Output() newContent: EventEmitter < any > = new EventEmitter();
   
  constructor(private postService: PostsService) { }

  ngOnInit(): void {
  }

publishNewPost() {
    this.postService.createPost(this.model).subscribe(newPost => {
      this.model = newPost;
      this.newContent.emit(this.model);
      this.router.navigateByUrl('/posts');      
    });
}
  posts: Post[];
  pagination: Pagination;
  postParams: PostParams = new PostParams();

  constructor(private postService: PostsService) { }

  ngOnInit(): void {
    this.loadPosts();
  }

  loadPosts() {
    this.postService.getPosts(this.postParams).subscribe(posts=> {
      this.posts = posts.result;
      this.pagination = posts.pagination;
     });
  }
<div>
     <span *ngFor="let post of posts">
          <app-post-card (newContent)="loadPosts($event)" [post]="post"></app-post-card>
     </span>
</div>

Source: Angular Questions

Published
Categorized as angular, refresh, routes Tagged , ,

Answers

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq