首页 > 解决方案 > 在 Angular 中重新路由后重新加载数据

问题描述

我创建了两个独立的 Angular 组件:PostList 和 PostCreate。PostCreate 用于创建新帖子,PostList 用于从数据库中检索帖子并显示所有帖子。在我按下在 PostCreateComponent 中创建帖子的按钮后,我被重定向到我的 PostList 组件,我希望看到显示的新帖子,而无需手动刷新页面。我已经尝试过window.location.reload()了,它确实可以工作,但是速度很慢并且会进行两次刷新。我可以让这更快吗?我也尝试过使用@Output,但它不起作用,因为 PostCreateComponent 不是 PostListComponent 的子组件。这是 PostCreateComponent:

import { Component, OnInit, Output } from '@angular/core';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { Pagination } from 'src/app/_models/pagination';
import { Post } from 'src/app/_models/post';

@Component({
  selector: 'app-post-create',
  templateUrl: './post-create.component.html',
  styleUrls: ['./post-create.component.css']
})
export class PostCreateComponent implements OnInit, OnDestroy {

  model: any = {};
   
  constructor(private postService: PostsService, private router: Router) { }

  ngOnInit(): void {
  }

  createPost(model: any) {
    this.postService.createPost(model).subscribe(post => {
      this.model = post;
      this.router.navigateByUrl('/posts')
      .then(() => {
         window.location.reload();
       });
    }, error => {
      console.log(error);
      this.toastr.error(error.error);
    });
  }

}
<form #postForm="ngForm" (ngSubmit)="createPost(this.model)" autocomplete="off">
    <div class="form-group">
        <input class="title form-control" name="title" [(ngModel)]="model.heading">
    </div>

    <div class="form-group">
        <textarea class="form-control" name="text" [(ngModel)]="model.body"> 
        </textarea>
    </div>

    <div class="form-group">
        <button type="submit" class="btn">Post</button>
    </div>
</form>

这是 PostListComponent:

import { Component, Input, OnInit } from '@angular/core';
import { Pagination } from 'src/app/_models/pagination';
import { Post } from 'src/app/_models/post';
import { PostParams } from 'src/app/_models/postParams';
import { PostsService } from 'src/app/_services/posts.service';

@Component({
  selector: 'app-post-list',
  templateUrl: './post-list.component.html',
  styleUrls: ['./post-list.component.css']
})
export class PostListComponent implements OnInit {
  posts: Post[];
  pagination: Pagination;
  postParams: PostParams = new PostParams();

  constructor(private postService: PostsService) { }

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

  loadPosts() {
    this.postService.getPosts(this.postParams).subscribe(response => {
      this.posts = response.result;
      this.pagination = response.pagination;
     });
   }
 }
 <div  class=" container mt-3" >
      <span *ngFor="let post of posts">
            <app-post-card [post]="post" class="item" ></app-post-card>
      </span>
 </div>  

标签: angularroutesreload

解决方案


推荐阅读