【问题标题】:How do I reload data after deletion?删除后如何重新加载数据?
【发布时间】:2021-07-20 15:23:57
【问题描述】:

我在我的应用程序中创建了一些作为 html 卡片的帖子。我有一个名为 PostList 的组件,我在其中显示所有这些卡片。在每张卡片上,我都有一个删除按钮来删除该特定卡片,这很有效,但是在我删除一张卡片后,它不会从我的帖子列表中消失,直到我手动刷新页面。这是我的名片:

<div class="card-body">
      <h5 class="card-title cut_text">{{post.title}}</h5>
      <p class="card-text cut_text" style="text-align: left;">
        {{post.text}}
      </p>
      <a href="#" class="btn btn-primary read" routerLink='/posts/{{post.id}}' style="justify-content: center;"><span>Read more</span></a>
      <button *appHasRole='["Admin"]' class="ml-5" (click)="deletePost(post.id)" type="button" style="box-shadow: 1px 1px grey;"><em class="fa fa-trash"></em></button>
</div>

这是删除功能:

@Component({
  selector: 'app-post-card',
  templateUrl: './post-card.component.html',
  styleUrls: ['./post-card.component.css']
})
export class PostCardComponent implements OnInit {
  @Input() post: Post;
  posts: Post[];
  model: any = {};
  user: User;
  postId: number;

  constructor(private postService: PostsService, private toastr: ToastrService, 
      private route: ActivatedRoute, public accountService: AccountService) {}

 ngOnInit(): void {

    this.route.params.subscribe((params) => {
      console.log(params);
      this.postId = params['id'];
    });
}
deletePost(id: number) {
    this.postService.deletePost(id).subscribe(() =>{
      this.toastr.success('Deleted');
    }, error => {
      console.log(error);
      this.toastr.error(error.error);
    });
  }
}

这是帖子列表的html:

 <div  class=" container mt-3" >
        <span *ngFor="let post of posts">
            <app-post-card [post]="post" class="item" ></app-post-card>
        </span>
 </div> 

这是加载帖子的方法:

export class PostListComponent implements OnInit {
  posts: Post[];
  post: 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;
    });
  }

}

我试过删除卡片后调用loadPosts()方法,虽然效率不高,但还是不行,还是要刷新页面。我该怎么做才能让它在我删除后自动消失?

【问题讨论】:

标签: html angular typescript reload


【解决方案1】:

您可以使用子组件中的@Output 发送已删除的id,并从父组件中的posts 变量中移除与此id 对应的元素。

post-card.component.ts

import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-post-card',
  templateUrl: './post-card.component.html',
  styleUrls: ['./post-card.component.css']
})
export class PostCardComponent implements OnInit {
  @Input() post: Post;
  @Output() postRemoved = new EventEmitter();     // <-- custom event

  posts: Post[];
  model: any = {};
  user: User;
  postId: number;

  constructor(private postService: PostsService, private toastr: ToastrService, 
      private route: ActivatedRoute, public accountService: AccountService) {}

  ngOnInit(): void {
    this.route.params.subscribe((params) => {
      console.log(params);
      this.postId = params['id'];
    });
  }

  deletePost(id: number) {
    this.postService.deletePost(id).subscribe(() =>{
      this.toastr.success('Deleted');
      this.postRemoved.emit(id);           // <-- emit the id in the event
    }, error => {
      console.log(error);
      this.toastr.error(error.error);
    });
  }
}

post-list.component.html

<div  class=" container mt-3" >
  <span *ngFor="let post of posts">
    <app-post-card (postRemoved)="onPostRemoved($event)" [post]="post" class="item" ></app-post-card>
  </span>
</div> 

post-list.component.ts

onPostRemoved(id: any) {
  this.posts = JSON.parse(JSON.stringify(     // <-- assign a deep clone   
    this.posts.filter(post => post.id !== id)
  ));
}

【讨论】:

  • 我可以在创建新帖子并将其添加到帖子列表后使用相同的策略进行刷新吗?对于这个方法createPost() { this.postService.createPost(this.model).subscribe(post =&gt; { this.model = post; this.toastr.success('Created'); this.router.navigateByUrl('/posts'); }, error =&gt; { console.log(error); this.toastr.error(error.error); }); }?
  • 是的,您可以将其发送给父级并使用this.posts = [...this.posts, post] 将其附加到posts 变量中。您还可以使用JSON.parse(JSON.stringify()) 创建深度克隆。
  • 好的,但是由于分页,我不能在 loadPosts() 方法的 PostList 组件中使用 this.posts = [...this.posts, post]
猜你喜欢
  • 2017-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多