Angular - Issue with deleting data using HTTPClientModule

I've encountered a strange issue with my Angular app where the delete request is not functioning as expected without any visible errors. Here's the code snippet from my service:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class TodoService {

  todoUrl = 'https://example.herokuapp.com/api/todoDB/';

  constructor(private http: HttpClient) { }

  getTodo() {
    return this.http.get(this.todoUrl);
  }

  postTodo(todoObject: any) {
    return this.http.post(this.todoUrl , todoObject);
  }

  deleteTodo(id: any) {
    const url = `${this.todoUrl}${id}`;
    console.log(url);    // *** This is printing correct URL
    return this.http.delete(url);
  }

}

Although getTodo() and postTodo() functions are working perfectly, the deleteTodo() method seems to be malfunctioning without any error indications. Strangely, manually testing the URL logged in console.log(url) using Postman works fine but it fails when called from the app. In my component, I'm using the following code to trigger the deleteTodo() method of my service:

removeTodo(i: any) {
    this.todoService.deleteTodo(this.todoArray[i]._id);
}

This is the delete route on my server:

// Delete Todo
router.delete('/:id' , (req , res) => {
    Todo.findById(req.params.id)
        .then((todo) => todo.remove().then(() => res.json({success : true})))
        .catch(err => res.json({success : false}).status(404))
});

Answer №1

To solve your issue, it is necessary to subscribe to the Observable

Here is a code snippet that can help with your problem:

removeTodo(i: any) {
    this.todoService.deleteTodo(this.todoArray[i]._id).subscribe(e=>{
    // Implement callback function here
    // Perform necessary actions after deleting the ID from the TODO list
    });
}

For more information, you can refer to the following resources:

Pluralsight guide on posting, deleting, and putting data in Angular

Angular documentation on making a delete request using HTTP

Answer №2

Update your code to include catchError and throwError with the usage of pipe for debugging purposes.

import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
removeTask(id: any) {
    const url = `${this.taskUrl}${id}`;
    return this.http.delete(url).pipe(
        catchError((err) => {
          console.log('error caught in service')
          console.error(err);
          return throwError(err);    //Throw it back to component
        })
      );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Validating Email Addresses Using JavaScript Regex

As a beginner to regex, I am just trying to validate if ([email protected]) works correctly. This is what I have attempted so far. var checkEmail = /^\w+@\w+\.[a-zA-Z]/; Is the above regex pattern suitable for my validation needs? ...

Transform the JSON structure with the power of JavaScript

Seeking assistance in converting the following array of JSON using either javascript or jquery: [ [{"day1":10,"day2":154,"day3":24,"day4":48,"day5":154,"day6":48,"day7":154,"name":"Packet"}], [{"day1":10,"day2":154,"day3":24,"day4":48,"day5":154,"day6":4 ...

ghost.py version 0.2.3 encountered a TimeoutError while trying to load the requested page

I'm currently using ghost.py Version: 0.2.3 and I am trying to retrieve the value of a JavaScript variable from a specific web page. However, when I execute this simple script, I encounter an error message saying "Unable to load requested page": from ...

Caution in NEXTJS: Make sure the server HTML includes a corresponding <div> within a <div> tag

Struggling with a warning while rendering pages in my Next.js and MUI project. Here's the code, any insights on how to resolve this would be greatly appreciated! import "../styles/globals.scss"; import { AppProps } from "next/app"; ...

Is there a way to automatically refresh random data from the server to the web client without the need for manual browser refresh?

Looking to send random data from the server to the web client without reloading the browser? Well, I've got you covered. Using a combination of web framework express.js, template engine pug.js, socket.io, and jQuery, you can achieve this seamlessly. ...

Obtaining child component references in Angular using @ViewChildren

Currently, I am generating several ModuleItemComponents by utilizing the following Angular syntax: <div #moduleItems *ngFor="let module of seriesItem.modules; let i = index"> <app-module-item [videoModule]="module" >< ...

The div displays the previous page, while the datatables feature showcases the information on the last page

Is there a way to navigate back to the previous page displayed in a div without using the History Back method? I am loading pages via ajax into the div which means there is no browser history saved. Currently, I am using a link to open the older page but I ...

Easy method for generating a JavaScript dictionary using an array containing arrays

I have a collection of paired items, and I am looking to convert it into a dictionary. const collection = [['apple', 3], ['banana', 5]] const transformed = {'apple': 3, 'banana': 5} If I were using Python, I could ...

Are the libraries imported within lazy loaded modules found in vendor.bundle.js?

Does the vendor.bundle.js file only consist of libraries that are imported within AppModule? I have removed all content from app.module.ts and noticed that the size of vendor.bundle.js is 9.5MB when using ng serve, but reduces to 3.22MB when using ng bui ...

Is it possible for NodeJS to redirect to an Angular5 route and return JSON instead of a webpage?

When using the API, I'm attempting to redirect a user if it is detected that they are no longer logged in. For example, if a user initiates an action (PUT) to the api, the API verifies the user's status. If the user is logged in, the action is ca ...

Issue encountered while generating a package using npm init in Node.js

I am currently in the learning process of NodeJs from tutorialspoint(TP). Following instructions provided in this link, I tried to create a package by running the following command: C:\Program Files (x86)\nodejs>npm init This utility will w ...

How can I specifically disable the next month in MUI Datepicker?

Employing MUI version 5, how can I disable only the next month in the datepicker while keeping the others functional? ...

Guide on transferring individual key values from an array to another array sequentially by clicking a button in Angular/JavaScript

I have an array of objects called marrayval. From this array, I want to extract the 'country' values one by one and push them into the arrayval after each click event. For example, on the first click, I would push C1, on the second click C1, C2, ...

Encountered an error while trying to find the Node JavaScript view

Whenever I attempt to render the URL for displaying index.js in the browser, an error arises: **Error:** Failed to locate view "index" in views directory "D:\NodeJs\Example\5expressnodjsexmp\views" Below is my application code: //Hea ...

Display a hidden form field in Rails depending on the object's value

As a programmer learning Ruby on Rails without much knowledge of Javascript, I faced a problem with a form that creates an object called Unit. This Unit model is related to Category which in turn is related to Product. The issue was that while selecting a ...

What is the best way to send numerous forms to a PHP page when the quantity of forms produced varies randomly?

In my project, I have a code that dynamically populates input fields at the final step based on a user's selection. Each choice can have up to 6 input fields, resulting in a maximum of 4 forms or 24 input fields in total. For data persistence, I need ...

Utilizing an AwsCustomResource in AWS CDK to access JSON values from a parameter store

I found a solution on Stack Overflow to access configurations stored in an AWS parameter. The implementation involves using the code snippet below: export class SSMParameterReader extends AwsCustomResource { constructor(scope: Construct, name: string, pr ...

The conundrum of Content-Type in Angular 8's HttpClient Post request

Seeking assistance with POST request to backend API! I'm encountering a 415 status code due to the content-type being sent as "text/plain" when the endpoint expects application/json. Interestingly, the POST works in PostMan (see screenshot below). I ...

Show the outcome of a function inside an ng-repeat loop

I have encountered a roadblock in my Angular project. I am populating a table with run data retrieved from a REST call using ng-repeat. Each run includes GPS coordinates, and I have a function that converts these coordinates into the corresponding city nam ...

Personalized HTML selection list

When a select option is too long, it stretches the container to accommodate its length. I have created a truncate function to limit the display to 20 characters and add ellipses to prevent this stretching. I have been searching for a way to show the entir ...