删除 angular 10 中的相应图像

Delete respective image in angular 10

试图通过 Id 删除相应的图像,但每次我单击删除按钮时它都会删除第一张图像。下面是我试过的代码。

获取图片

imageId: number;

this.imageService.getImage(this.productId).subscribe(m => {
  this.imageData = m;
  this.imageId = this.imageData[0].Id;
  console.log(m);
  console.log('ImageId ' + this.imageId);
});

删除方法

deleteImage() {
  this.imageService.deleteImage(this.imageId).subscribe(d => {
    console.log('Image removed')
  }, error => {
    console.log(error);
  });
}

Html

<div class="container">
  <div *ngFor="let img of imageData">
    <p [hidden]="true">{{img.Id}}</p>
    <img class="original" [alt]="img.Name" 
    src="https://localhost:44349/{{img.ImagePath}}" 
    width="350" 
    height="350" />
    <button type="submit" (click)="deleteImage()" class="btn btn-danger">
      <i class="far fa-trash-alt"></i>
      Remove
    </button>
  </div>
</div>

将 id 传递给函数,您实际要删除的 id,现在您正在使用一些变量 this.imageId。所以在你的模板中,传递 id:

(click)="deleteImage(img.Id)"

并在删除中使用该参数:

deleteImage(id) {
  this.imageService.deleteImage(id).subscribe(d => {
   console.log('Image removed')
}, error => {
  console.log(error);
});

获取图像

this.imageService.getImage(this.productId).subscribe(m => {
  this.imageData = m;
});

删除方法

deleteImage(Id: any):any {
    this.imageService.deleteImage(Id).subscribe(d => {
      console.log('Image removed')
    }, error => {
      console.log(error);
    });
}

HTML

<div class="container">
  <div *ngFor="let img of imageData">
    <p [hidden]="true">{{img.Id}}</p>
    <img class="original" [alt]="img.Name" 
    src="https://localhost:44349/{{img.ImagePath}}" 
    width="350" 
    height="350" />
    <button type="submit" (click)="deleteImage(img.Id)" class="btn btn-danger">
      <i class="far fa-trash-alt"></i>
      Remove
    </button>
  </div>
</div>