【问题标题】:How to create an if else statement to delete item from angular如何创建 if else 语句以从角度删除项目
【发布时间】:2020-05-25 10:17:35
【问题描述】:

如果项目的数量为 0,我正在尝试删除项目,但如果项目的数量不是 = 0,则无法删除它并向前端发送错误消息

这是我的 components.ts:

  productID: string;
  productData: any;
  error = "";

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private httpService: HttpService
  ) {}

  ngOnInit() {
    this.productID = this.route.snapshot.paramMap.get("id");
    this.getOneProduct();
  }

  getOneProduct() {
    let observable = this.httpService.oneProduct(this.productID);
    observable.subscribe((data) => {
      this.productData = data;
    });
  }

  onDelete(id) {
    const observable = this.httpService.deleteProduct(id);
    observable.subscribe((data: any) => {
      if (data.qty < 0) {
        this.error = "Qty need to be 0 to delete item";
        this.router.navigate([`products/${id}`]);
      } else {
        this.router.navigate(["products"]);
      }
    });
  }

这是我的 HTML 代码:

  <div *ngIf="error">
    <p class="text-danger">{{error}}</p>
  </div>
  <div class="info" *ngFor="let product of productData">
    <h5> Name: {{product.name}}</h5>
    <h5> Qty: {{product.qty}}</h5>
    <h5> Price: ${{product.price}}</h5>

    <button class="btn btn-secondary" [routerLink]="['/products']">Back</button>
    <button class="btn btn-danger" id="delete" (click)="onDelete(product._id)">Delete</button>
  </div>

【问题讨论】:

  • 究竟是什么不起作用?
  • 按钮删除项目!即使项目的数量不是 0,它也能正常工作

标签: html angular mongodb express


【解决方案1】:

在你的 onDelete 方法中,改变这个:

if (data.qty &lt; 0) {...}

这意味着你要删除所有超过0的东西,通过:

if (data.qty === 0) {...}

也反转你的条件。如果 qty === 0 则删除,否则抛出错误。

此外,您应该在进行任何 http 调用之前检查产品数量。有了id就可以轻松搞定,避免无用的api调用。

【讨论】:

    【解决方案2】:

    应该是 if (data.qty > 0){. //Show error..} else{..delete..}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-29
      • 2019-08-28
      • 1970-01-01
      • 2016-02-04
      • 1970-01-01
      • 2019-04-09
      相关资源
      最近更新 更多