【问题标题】:How to auto refresh list after delete item with button click单击按钮删除项目后如何自动刷新列表
【发布时间】:2019-10-28 15:57:23
【问题描述】:

我的后端有一条使用其 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);
      }
    );
  }
}

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

【问题讨论】:

  • 删除文章后,请更新您的this.data_array。我不确定deteleArticle 方法的响应是什么,或者其他替代方法是再次调用服务getArticles(),它将检索您更新的数据并使用输出发射器将其发送回mat-list-item

标签: javascript angular


【解决方案1】:

在您的文章组件中,您可以在删除项目的调用完成时在 delete 方法中添加一个事件并触发,然后在 articleListComponent 中订阅该事件。当 articleListComponent 中订阅事件的方法运行时,识别出从数组中删除的元素并将其也从那里删除。 您可以在事件中返回已删除项目的 id 并在数组中搜索它。请记住,当您从数组中删除项目时,您的视图不会为对数组的引用而刷新。您必须用剩余的项目创建一个新数组。

你可以这样做

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

【讨论】:

    【解决方案2】:

    你需要再次调用这个方法:

    getAllPost()

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

    【讨论】:

      【解决方案3】:

      为此,您必须在 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()
      }
      

      希望这会对你有所帮助。

      【讨论】:

      • 我这样做了,正在从数据库中删除,但没有刷新列表,我必须手动重新加载它
      猜你喜欢
      • 2019-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多