Angular 中的条件不正常

condition not working as spect in Angular

我正在尝试使用 Angular 10 创建条件以检查 asp.net 核心 3 api 的数据是否存在,但仅在返回和 post 在下面的 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 一起使用,但它仅在没有看到 else 时返回。

您在 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));
  });
}});}