For recent versions of Angular (v13), the code is a bit different. Let's start with the service implementation:
import { NotFoundError } from './../common/not-found-error';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
import { AppError } from '../common/app-error';
...
deletePost(id: number) {
return this.http.delete(this.url + '/' + id).pipe(
catchError((error: Response) => {
if (error.status === 404)
return throwError(() => new NotFoundError(error));
return throwError(() => new AppError(error));
})
);
}
For a Separation of concerns purpose, the service is responsible for sending the delete request and catching any potential known (not found 404) or unknown error. In case of an error, the service throws an error by calling one of the application error classes (AppError which is a generic class and NotFoundError which is a specific error class and it extends AppError).
Note that the service delegates the error management to thoses 2 error application classes (the service role is not to go into error management details)
AppError (app-error.ts):
export class AppError {
constructor(public originalError?: any) {}
}
NotFoundError (not-found-error.ts):
import { AppError } from './app-error';
export class NotFoundError extends AppError {}
Now for the posts.component.ts implementation, we should have something like:
import { NotFoundError } from './../common/not-found-error';
import { AppError } from './../common/app-error';
...
deletePost(post: any) {
this.service.deletePost(post.id).subscribe({
next: () => {
let index = this.posts.indexOf(post);
this.posts.splice(index, 1);
},
error: (error: AppError) => {
if (error instanceof NotFoundError)
alert('this post has already been deleted');
else {
alert('An unexpected error occured.');
console.log(error);
}
},
});
}
This deletePost method subscribes to the dedicated service, and in case the service catches and throws an error, deletePost will check the kind of the error and will show the error accordingly.
npm install
to get all dependencies – Luchoimport { Observable } from 'rxjs';
– Lucho