繁体   English   中英

如何在按钮单击后删除项目后自动刷新列表

[英]How to auto refresh list after delete item with button click

我的后端有一个使用其id删除文章的路径,现在在Angular我有这个文章列表,当我点击它时每行都有一个按钮我想从数据库中删除这篇文章,好我已经完成了这个然后事情是文章列表不自动刷新所以删除的文章仍然存在

我有2个方法的ArticleService文件:1用于获取所有文章(这是在启动应用程序时调用的)和删除文章1,我希望在成功删除文章后文章列表显示没有更多文章没有我不得不手动刷新页面

这是我的ArticleService文件:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Observable } from "rxjs";
import { Article } from '../models/article';

@Injectable({
  providedIn: 'root'
})
export class ArticleService {
  private url: string;
  constructor(private _http:HttpClient) {
    this.url = 'http://localhost:3000/api/';
  }

  getArticles(){
    let headers = new HttpHeaders().set('Content-Type', 'application/json');
    return this._http.get(this.url + 'get-articles', {headers:headers});
  }
  deteleArticle(id:any){
    console.log('Voy a borrar el articulo con id ' + id);
    let headers = new HttpHeaders().set('Content-Type', 'application/json');
    return this._http.delete(this.url + 'delete-article/' + id, {headers:headers});
  }
}

文章组件html:

<div class="actions-container" id="deletebtn">
        <button mat-icon-button color="warn" (click)="deleteArticle(data._id)">
            <mat-icon>delete_forever</mat-icon>
        </button>
    </div>

ArticlesListComponent.html

<mat-list>
    <mat-list-item *ngFor="let article of data_array">
        <app-article [data]='article'></app-article>
    </mat-list-item>
</mat-list>

ArticleComponent.ts

import { Component, OnInit,Input } from '@angular/core';
import { DatePipe } from '@angular/common';
import { ArticleService } from '../shared/article.service';

@Component({
  selector: 'app-article',
  templateUrl: './article.component.html',
  styleUrls: ['./article.component.css']
})
export class ArticleComponent implements OnInit {
  @Input() data: any;
  constructor(
    private datePipe: DatePipe,
    private _articleService: ArticleService) { }

  ngOnInit() {
  }

  public deleteArticle(id):void{
    this._articleService.deteleArticle(id).subscribe(response=>{
      console.log(response);
    },error=>{
      if(<any>error){
        console.log(error);
      }
    });
  }
}

和ArticlesListComponent.ts

import { Component, OnInit } from '@angular/core';
import { ArticleService } from '../shared/article.service';

@Component({
  selector: 'app-articles-list',
  templateUrl: './articles-list.component.html',
  styleUrls: ['./articles-list.component.css'],
  providers:[ArticleService]
})
export class ArticlesListComponent implements OnInit {

  public data_array = [];
  constructor(private articleService: ArticleService) { }

  ngOnInit() {
    console.log('Article-List component ready.');
    this.getAllPost();
  }

  getAllPost(){
    this.articleService.getArticles().subscribe(
      result => {
        this.data_array = result['articles'];
      },
      error=>{
        console.log(error);
      }
    );
  }
}

如何刷新列表或删除文章后如何操作

在您的文章组件中,您可以在删除项目的调用完成时在delete方法中添加事件和触发器,然后在articleListComponent中继承该事件。 当postListComponent中的方法停止运行时,标识从数组中删除的元素并从那里删除它。 您可以在事件中返回,删除项目的ID并在数组中搜索它。 请记住,从阵列中删除项目时,对于数组的引用不会刷新视图。 您必须使用其余项目创建一个新数组。

你可以这样做

  this.data_array  = [...this.data_array];

您需要再次调用此方法:

getAllPost()

因为你有一个共享服务deleteArticle()方法的成功,你可以调用getAllPost()方法,它将刷新你的列表。

要做到这一点,你必须在ArticleComponent.ts中输出EventEmitter

 @Output() public handleDelete: EventEmitter<any> = new EventEmitter<any>();

成功删除记录时,使用已删除的元素ID发出此事件

public deleteArticle(id):void{
    this._articleService.deteleArticle(id).subscribe(response=>{
    this.handleDelete.emit(id);  
      console.log(response);
    },error=>{
      if(<any>error){
        console.log(error);
      }
    });
  }

在ArticlesListComponent.html中添加(handleDelete)=“deleteHandle($ event)”

 <mat-list>
        <mat-list-item *ngFor="let article of data_array">
            <app-article [data]='article' (handleDelete)="deleteHandle($event)"></app-article>
        </mat-list-item>
    </mat-list>

在ArticleComponent.ts中添加deleteHandle方法,因为我们可以从data_array中删除已删除的元素以防止其他服务器调用,或者您可以调用刷新列表的getAllPost()

deleteHandle(id)
{
    var index = data_array.indexOf(e => e._id ==id);

    if (index > -1) {
       data_array.splice(index, 1);
    }
}

要么

deleteHandle(id)
{
   this.getAllPost()
}

希望这会帮助你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM