首页 > 解决方案 > 条件在 Angular 中无法正常工作

问题描述

我正在尝试使用 Angular 10 来检查带有 asp.net core 3 api 的数据是否存在,但只有在返回和发布时才放入,否则在下面的 TS 代码中不起作用

handleAddToCart() {
    let checking = this.CartService.getCartItemByItemId(this.productItem.itemLookupCode, this.cartForm.value.weight, this.productItem.storeId)
    .subscribe(c=>{
      return c;
    });
    if (checking ) {
      const updateCartPost = {
        itemID: this.productItem.itemID,
        itemLookupCode: this.productItem.itemLookupCode,
        categoryID: this.productItem.categoryID,
        departmentID: this.productItem.departmentID,
        itemDescription: this.productItem.itemDescription,
        subDescription3: this.productItem.subDescription3,
        quantity: this.cartForm.value.qty,
        weight: this.cartForm.value.weight,
        snapShotPrice: this.productItem.snapShotPrice,
        storeId: this.productItem.storeId,
        barcode: this.productItem.barcode,
        email: localStorage.getItem('email'),
        itemImage: ''
      }
      this.CartService.updateCartItem(updateCartPost).subscribe(u => {
        this.msg.sendMsg(this.AddToCart(this.cartForm.value.weight));
        this.toaster.success('Added To Cart');
        console.log('sssssr');
      });

    }
else{
      this.CartService.addProductToCart(this.AddToCart(this.cartForm.value.weight)).subscribe(() => {
        this.msg.sendMsg(this.AddToCart(this.cartForm.value.weight));
        this.toaster.success('Added To Cart');
        console.log(this.AddToCart(this.cartForm.value.weight));
      });
}
  }

谁能帮我?

我需要将条件与 if 和 else 一起使用,但它只返回 if 并且没有看到 else。

标签: typescriptangular9angular10

解决方案


您在 if 条件中检查的变量checking将始终为真,因为它是订阅类型。您可能正在寻找这个逻辑:

handleAddToCart() {
let checking = this.CartService.getCartItemByItemId(this.productItem.itemLookupCode, this.cartForm.value.weight, this.productItem.storeId)
.subscribe(c=>{
  if (c ) {
  const updateCartPost = {
    itemID: this.productItem.itemID,
    itemLookupCode: this.productItem.itemLookupCode,
    categoryID: this.productItem.categoryID,
    departmentID: this.productItem.departmentID,
    itemDescription: this.productItem.itemDescription,
    subDescription3: this.productItem.subDescription3,
    quantity: this.cartForm.value.qty,
    weight: this.cartForm.value.weight,
    snapShotPrice: this.productItem.snapShotPrice,
    storeId: this.productItem.storeId,
    barcode: this.productItem.barcode,
    email: localStorage.getItem('email'),
    itemImage: ''
  }
  this.CartService.updateCartItem(updateCartPost).subscribe(u => {
    this.msg.sendMsg(this.AddToCart(this.cartForm.value.weight));
    this.toaster.success('Added To Cart');
    console.log('sssssr');
  });

}
else{
  this.CartService.addProductToCart(this.AddToCart(this.cartForm.value.weight)).subscribe(() => {
    this.msg.sendMsg(this.AddToCart(this.cartForm.value.weight));
    this.toaster.success('Added To Cart');
    console.log(this.AddToCart(this.cartForm.value.weight));
  });
}});}

推荐阅读