Niko Bellic
Niko Bellic

Reputation: 59

Angular - HTTPClientModule delete request not working

I am making a simple delete request from my angular app but nothing is happening and no error is appearing. My service code is as follows :

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

}

My getTodo() and postTodo() are working completely fine but the deleteTodo() method is not working and also it does not show any error either. When I put the URL from the console.log(url) in postman, it works but it is not working from my app.I am using the following code in my component to access the deleteTodo() method of my service :

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

My delete route of 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))
});

Upvotes: 1

Views: 312

Answers (2)

Shankar Ganesh Jayaraman
Shankar Ganesh Jayaraman

Reputation: 1501

Modify your code to support catchError and throwError using pipe for debugging.

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

Upvotes: 0

Amit K Khanchandani
Amit K Khanchandani

Reputation: 355

You need to subscribe to the Observable

Code Snippet for your problem:

removeTodo(i: any) {
    this.todoService.deleteTodo(this.todoArray[i]._id).subscribe(e=>{
    // Callback
    // Perform Actions which are required after deleting the id from the TODO
    });
}

Additional Reference:

https://www.pluralsight.com/guides/posting-deleting-putting-data-angular

https://angular.io/guide/http#making-a-delete-request

Upvotes: 2

Related Questions