【问题标题】:Delete respective image in angular 10删除角度为 10 的相应图像
【发布时间】:2021-07-25 01:27:20
【问题描述】:

尝试按 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>

【问题讨论】:

    标签: angular angular11


    【解决方案1】:

    将 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);
    });
    

    【讨论】:

      【解决方案2】:

      获取图片

      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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-08
        • 2016-06-25
        • 1970-01-01
        • 2013-01-20
        • 2021-08-11
        • 1970-01-01
        • 2021-08-28
        相关资源
        最近更新 更多