Angular DELETE request sends 'undefined' ID (400 Bad Request)

Discussão em 'Angular' iniciado por Ammar, Abril 2, 2025.

  1. Ammar

    Ammar Guest

    I am working on an Angular application where I am trying to delete and edit a product using an API call. However, I am getting a 400 Bad Request error because the DELETE request URL contains undefined instead of the actual product ID. How do i fix the issue of Id being passed as undefined?

    Error Message

    DELETE http://localhost:5180/api/Product/DeleteProduct/undefined 400 (Bad Request)
    HttpErrorResponse {status: 400, statusText: 'Bad Request', url: 'http://localhost:5180/api/Product/DeleteProduct/undefined'}


    Angular Component (product.component.ts)

    deleteProduct(id: number) {
    console.log("Deleting product with ID:", id);
    if (id === undefined || id === null) {
    console.error("Product ID is undefined or null");
    return;
    }
    this.dataService.deleteProduct(id).subscribe({
    next: (response) => {
    alert("Deleted");
    // this.GetProducts();
    window.location.reload();
    },
    error: (err) => {
    console.error("Error deleting product", err);
    }
    });
    }


    Service (data.service.ts)

    deleteProduct(id: number): Observable<Product> {
    return this.httpClient.delete<Product>(`${this.apiUrl}Product/DeleteProduct/${id}`);
    }


    API Endpoint

    [HttpDelete]
    [Route("DeleteProduct/{productId}")]
    public async Task<IActionResult> DeleteProduct(int productId)
    {
    try
    {
    var existingProduct = await _productRepo.GetProductAsync(productId);
    if (existingProduct == null) return NotFound($"The product does not exist");
    _productRepo.Delete(existingProduct);

    if(await _productRepo.SaveChangesAsync()) return Ok(existingProduct);
    }
    catch (Exception)
    {

    return StatusCode(500, "Internal Server Error. Please contact support.");
    }

    return BadRequest("Your request is invalid");
    }


    html <button class="btn-delete" (click)="deleteCourse(course.courseId)">Delete

    Continue reading...

Compartilhe esta Página