Angular version 10 does not allow for intentionally causing errors using the HttpClient delete() method

Currently, I'm working through an Angular tutorial and facing a challenge in the error-handling section. Despite my efforts to trigger an error with incorrect data in a HttpClient.delete()-request, I am unable to force one.

To provide some context, I am retrieving my data (posts) from http://jsonplaceholder.typicode.com/posts.

Even after attempting to input invalid ids into the delete-function at various points, such as out-of-bound ids or '1' which should be deletable upon two button clicks, no errors are being generated.

Instead of throwing an error, the functionality is performing as expected by clearing out the posts-list and precisely deleting the selected posts upon clicking.

I went further to simplify the process by eliminating error-services and consolidating actions within the posts-component without success.

View the excerpts below for reference:

posts.component.ts

import { BadInputError } from './../common/bad-input';
import { NotFoundError } from './../common/not-found-error';
import { PostService } from './../services/post.service';
import { Component, Input, OnInit } from '@angular/core';
import { AppError } from '../common/app-error';

@Component({
  selector: 'posts',
  templateUrl: './posts.component.html',
  styleUrls: ['./posts.component.css']
})
export class PostsComponent implements OnInit {
  posts: any[];
  constructor(private service: PostService) { }

  // ...

  deletePost(post) {
    this.service.deletePost(post.id).subscribe(
      response => {
        console.log(response);
        let index = this.posts.indexOf(post);
        this.posts.splice(index, 1);
      }, 
      (error: AppError) => {
        if (error instanceof NotFoundError)
          alert('This post has already been deleted.');
        else {
          alert('An unexpected error occured.');
          console.log(error);
        }
      }
    );
    console.log(this.posts);
  }
}

posts.component.html

<ul class="list-group">
    <li 
        *ngFor="let post of posts"
        class="list-group-item">
        <button 
            (click)="deletePost(post)"
            class="btn btn-default btn-sm">
            Delete
        </button>
        {{ post.title }}
    </li>
</ul>

post.service.ts

export class PostService {
  private url = 'http://jsonplaceholder.typicode.com/posts';
  constructor(private http: HttpClient) { }

  // ...

  deletePost(id) {
    return this.http.delete(this.url + '/' + id)
      .pipe(
        catchError((error: HttpErrorResponse) => {
          if (error.status === 404)
            // throw Observable.throw(new NotFoundError);
            throw throwError(error);
            //return Observable.throw(new NotFoundError);
          else
            return Observable.throw(new AppError(error));
        })
      );
  }
}

app-error.ts

export class AppError {
    constructor(public originalError?: any) {}
}

not-found-error.ts

import { AppError } from './app-error';

export class NotFoundError extends AppError {}

bad-input.ts

import { AppError } from './app-error';

export class BadInputError extends AppError {}

If anyone can shed light on where I might be going wrong and how I can intentionally trigger errors to test the application, it would be greatly appreciated.

Warm regards

Answer №1

Although this may not directly solve the issue I was facing, it did provide me with valuable insight on how to test my error handling.

I realized that I can simulate an error by purposely throwing one within the error-handling function before its main code is executed:

delete(id) {
  return throwError(new NotFoundError);

  return this.http.delete(this.url + '/' + id)
    .pipe(
      catchError(this.handleError)
    );
}

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

Converting JQueryPromise to Promise: A step-by-step guide

In my current project, there is a code snippet that produces a JQuery promise: const jqProm = server.downloadAsync(); I am interested in integrating this promise within an async function. I was thinking of creating something similar to the C# TaskComplet ...

Angular2 fire fails because the namespace 'firebase' does not export the member 'Promise'

I recently set up Angular 2 Fire on my project. "angularfire2": "^5.0.0-rc.0", Now, in my root module (app module), I have the following setup: export const firebaseConfig = { apiKey: "mykey", authDomain: "....", databaseURL: "...", projectId: ...

Using react-confetti to create numerous confetti effects simultaneously on a single webpage

I'm looking to showcase multiple confetti effects using the react-confetti library on a single page. However, every attempt to do so in my component seems to only display the confetti effect on the last element, rather than all of them. The canvas fo ...

Error: Cannot access Angular 5 Title service at this time

When attempting to change the page title using BrowserModule, I encountered an issue. I added the BrowserModule and Title in the application module as shown here: https://angular.io/guide/set-document-title However, in a child module where I tried to add ...

Error encountered in React component: TypeScript TS2339 states that the property 'xyz' is not found on type 'IntrinsicAttributes...'

I am attempting to develop a straightforward React component that can accept any properties. The syntax below using any is causing issues (unexpected token just before <): export class ValidatedInput extends React.Component<any, any> {...} The p ...

Validator checking the status of an Angular form

Currently working on developing a custom form validator. In my test component, there are three checkboxes. The main form should only be considered valid if at least one checkbox is checked. https://stackblitz.com/edit/stackblitz-starters-69q3rq Within th ...

Steps to set up Node.js Express.js for API, React.js for the front end, and Angular for the admin panel

Is there a way to deploy nodejs with SSL certificates? I am using expressjs for API, reactjs for front-end, and angular for backend. I need specific paths like for frontend, for admin, and the expressjs API running in the background with https, similar t ...

What steps do I need to take to create a customizable Angular Material NPM module?

Can a custom npm module be created using Angular Material that allows the components to be styled by the consuming app's unique theme? For instance, imagine an npm module with a component containing the following template: <button mat-raised-butt ...

Accessing nested JSON objects with key-value pairs

I have a method in my .ts file that displays keys but doesn't fetch nested JSON data. generateArr(obj) { return Object.keys(obj).map((key) => { console.log(key, obj[key]); return {key: key, value: obj[key]}; }); } Here is the HTML code I&apo ...

Calculate the total value of an object using Typescript

Here is the data that I have: [Products, Products, Products, Products] 0: Products {product_id: "1", Product_type_id: "11", Subtotal:450, …} 1: Products {product_id: "2", Product_type_id: "22", Subtotal:550, …} 2: Products {product_id: ...

The attempt to upload a file in Angular was unsuccessful

Below is the backend code snippet used to upload a file: $app->post('/upload/{studentid}', function(Request $request, Response $response, $args) { $uploadedFiles = $request->getUploadedFiles(); $uploadedFile = $uploadedFiles[&apo ...

Storing Passport.js Token Locally: Best Practices

Struggling to save the jwt token provided by passport.js in browser localStorage, I am facing challenges with transferring it from the server to the client as it is generated on the server side. If anyone can assist me with setting the server-generated to ...

Two primary router outlets featuring unique layouts

Design for all users Design for staff members (such as admin control panel) I am using a router-outlet with the first design. How can I switch to the second design at "/personnel"? I want to keep both designs intact since "personnel" has its own componen ...

Customize the height of individual carousel items in Primeng carousel

Hey there, I'm currently using the primeng carousel component and running into an issue where the carousel height is always based on the tallest item. I am looking to have an automatic height for each individual carousel item instead. Do you think th ...

Converting Angular 2/TypeScript classes into JSON format

I am currently working on creating a class that will enable sending a JSON object to a REST API. The JSON object that needs to be sent is as follows: { "libraryName": "temp", "triggerName": "trigger", "currentVersion": "1.3", "createdUser": "xyz", ...

The click event is activated following the :active selector being triggered

My Angular application features a button with a slight animation - it moves down by a few pixels when clicked on: &:active { margin: 15px 0 0 0; } The button also has a (click)="myFunction()" event listener attached to it. A common issue arises w ...

The powerful combination of Vuetify, Inertia, and Typescript creates a

Currently, I am working with Vuetify and Inertia while using Typescript. I am faced with the challenge of passing shared data to the items prop of a vuetify AutoComplete component: <v-autocomplete :items="$page.props.countries"></v-auto ...

Show detailed information in a table cell containing various arrays using AngularJS

After integrating d3.js into my code, I now have an array with key-value pairs. Each team is assigned a key and its corresponding cost is the value. When I check the console log, it looks like this: Console.log for key and value Rate for current month [{ ...

Browse through the options in the dropdown list -Angular 6

I am looking to implement a filtering feature in my Angular app where data can be filtered based on the selected product number from a dropdown menu. The product data is structured in JSON format as shown below. component.ts productlistArray = [{ num ...

Tips for utilizing [ngClass] with various class situations in Angular4

My current div structure is as follows: <div class="class-a" [ngClass]="{'class-b': !person.something}"> However, I now need to add an additional condition... I want the div to have class-a if one condition is met, class-b if another con ...