Search code examples
javascriptnode.jsangulartypescriptangular-httpclient

Do something after a DELETE request is complete with Angular HttpClient


I have a button which deletes an item on click. I want to show a simple alert('Item deleted') alert after the action is done. However I can't seem to make it work. Note that the item gets deleted.

Here's what I tried:

deleteItem function in my component

deleteItem(id: number) {
    this.eventsService
      .deleteEventById(id)
      .subscribe(
        res => console.log(res),
        err => console.log(err),
        () => alert('Item deleted')
      );
  }

Nothing is printed to the console and no alert is shown.

deleteEventById function in my service

deleteEventById(id: number) {
  return this.http
    .delete(`/api/events/${id}`, this.headerForPrivateCalls)
    .pipe(
      catchError(this.handleError),
    );
}

api route (if it matters)

router.delete('/events/:id', authCheck, (req, res) => {
    connection((client) => {
        client.db('gordes').collection('events')
        .deleteOne({id: +req.params.id})
        .then(() => {
            res.status(204);
        })
        .catch((err) => {
            sendError(err, res);
        });
    })
});

Solution

  • your deleteEventById service does not return anything to the Observable. You will need to add a .map()

        deleteEventById(id: number) {
           return (this.http
            .delete(`/api/events/${id}`, this.headerForPrivateCalls)
            .map(response => response.json())
            .pipe(
               catchError(this.handleError),
            );
          )
       }
    

    EDIT

    the problem seems to be in the node back-end :

    you dont return anything by

    res.status(204);
    

    use :

    res.status(204).send();