Delete method is not giving me an error since I am passing 1000 as an argument which is not present in the 'https://jsonplaceholder.typicode.com/posts' json document. Instead, it just removes the selected document. I searched everywhere but I didn't find any code which specifies how to resolve this problem. Any help would be appreciated as I am new to Angular Framework.
Below is my Code of Service file(post.service.ts)
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { catchError } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';
import { NotFoundError } from '../common/not-found-error';
import { AppError } from '../common/app-error';
import { BadInput } from '../common/bad-input';
// For handling Http Requests
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class PostService {
private url = 'https://jsonplaceholder.typicode.com/posts';
private userUrl = 'https://jsonplaceholder.typicode.com/users';
constructor(private http: HttpClient) {}
getPosts() {
return this.http.get(this.url);
}
deletePost(id) {
console.log('Service Id: ', id);
return this.http.delete(this.url + '/' + id)
.pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 404) {
console.log('You screwed');
return throwError(new NotFoundError());
}
return throwError(new AppError(error));
})
);
This is my Component File(post.component.ts)
deletePost(post) {
console.log('Post Id is: ', post.id);
this.service.deletePost(1000)
.subscribe(
response => {
let index = this.posts.indexOf(post);
this.posts.splice(index, 1);
console.log(response);
},
(error: AppError) => {
if (error instanceof NotFoundError) {
alert('This post has already been deleted');
} else {
alert('An Unexpected error occurred.');
console.log(error);
}
});
}
ngOnInit() {
this.service.getPosts()
.subscribe((response) => {
this.posts = response;
console.log('Posts: ', this.posts);
}, error => {
alert('An Unexpected error occurred.');
console.log(error);
});
}
This is my Component.html File(posts.component.html)
<ul class="list-group">
<li *ngFor="let post of posts" class="list-group-item">
<button (click)="deletePost(post)" class="btn btn-danger btn-sm">Delete</button>{{ post.title }}
</li>
</ul>
<br>
The API that you are invoking returns a JSONObject. Not an error. See the POSTMAN invocation of the API
Since this is not an error, CatchError is not executed.
UPDATE
Since there is no error, your success part executes. Which takes the index of the returned object in the existing posts
array. If you log the index to console, you can see it will be -1.
Without checking whether the index is found or not you are passing it to splice.
array.splice(-1,1)
will remove the last element from the array. Hence the li
element getting deleted.
More on Array.indexOf and Array.splice
You have to check whether the index of returned object is present in your array. then perform splice.