【问题标题】:Call ASP.NET Web API in Angular 8 not working [closed]在 Angular 8 中调用 ASP.NET Web API 不起作用 [关闭]
【发布时间】:2021-09-15 15:00:39
【问题描述】:

作为参考,我使用的是 SQL Server、EF 6 和 Angular 8。我的实体是客户、产品和愿望清单(有 wishIduserIdproductId)。但是我的代码不起作用,你们能帮忙吗?

控制器:

    [Route("AddToWishlist")]
    [HttpPost]
    public IHttpActionResult AddToWishlist(WishList wishlist)
    {
        db.WishList.Add(wishlist);
        db.SaveChanges();

        return Ok();
    }

product.service.ts:

getWishlist() {
 return this.http.get(wishlistUrl).pipe(
       map((result: any[]) => {
            let productIds = []

              result.forEach(item => productIds.push(item.id))

   return productIds;
   })
  )
  }

addToWishlist(productId) {
     return this.http.post(wishlistUrl, { id: productId })
}

removeFromWishlist(productId) {
   return this.http.delete(wishlistUrl + '/' + productId);
}

product.component.ts:

handleAddToWishlist() {
   this.wishlistService.addToWishlist(this.productItem.id).subscribe(() => { 
   this.addedToWishlist = true;
 })
}

 handleRemoveFromWishlist() {
   this.wishlistService.removeFromWishlist(this.productItem.id).subscribe(() => {
   this.addedToWishlist = false;
})

}

product.component.html:

<i *ngIf="addedToWishlist" class="fas fa-heart float-right" 
(click)="handleRemoveFromWishlist()"></i>
<i *ngIf="!addedToWishlist" class="far fa-heart float-right" 
(click)="handleAddToWishlist()"></i>

【问题讨论】:

  • “不工作”是什么意思?
  • 检查您的呼叫是否被 CORS 阻止。您是否在启动文件中添加了 CORS 中间件?

标签: c# asp.net sql-server angular typescript


【解决方案1】:

很多事情都可能导致此代码无法正常工作,我将在这里提到一些案例并尝试它们,这可能会有所帮助:-

  • 在后端方法中 AddToWishlist 没有错误句柄,因为该实体具有三个字段,并且您仅发布 { id: productId } 这将使 ef 保存更改失败
  • 从谷歌浏览器按 f12 并选择网络以监视网络请求以查看从后端收到的请求和响应,如果您发现网络响应符合预期,这将指导您原因可能在角度脚本的显示部分中李>
  • 最后,如果以前的 f12 不起作用,请选择 consol 以查看是否有 consol 错误,您是否会发现任何脚本错误或 cors 块

【讨论】:

    【解决方案2】:

    我只注意到一件事,可以为其他 API 调用指明正确的方向

    您添加到愿望清单,当您提到 API 需要 wishId 时,您只会传递“id”

    addToWishlist(productId) {
         return this.http.post(wishlistUrl, { wishId: productId })
    }
    

    其他建议

    为您的每个实体创建DTO 对象。

    API - WishListInfo.cs

    public class WishListInfo {
     public int wishId { get; set; }
    }
    

    UI(接口或类)

    export class WishListInfo {
     wishId: number;
    }
    

    现在您可以按如下方式更新对 api 的调用

    addToWishlist(wish: WishListInfo) { <- You will set this object before making this call.
         return this.http.post(wishlistUrl, wish)
    }
    
    [Route("AddToWishlist")]
        [HttpPost]
        public IHttpActionResult AddToWishlist(WishListInfo wishlist)
        {
            db.WishList.Add(wishlist);
            db.SaveChanges();
    
            return Ok();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多