I have this template showing these posts:
<div class="card mb-3" *ngFor="let post of posts">
<div class="card-body">
<h5 class="card-title">{{post.title}}</h5>
<p class="card-text">{{post.body}}</p>
<button (click)="removePost(post)" class="btn btn-danger"><i class="fa fa-remove"></i></button>
<button (click)="editPost(post)" class="btn btn-light"><i class="fa fa-pencil"></i></button>
</div>
</div>
The remove function is using a service named servicePost to remove posts
removePost(post: Post) {
if (confirm('Are you sure?')) {
this.postService.removePost(post.id).subscribe(() => {
this.posts.forEach((current, index) => {
if (post.id === current.id) {
this.posts.splice(index, 1);
}
});
});
}
}
And the service itself
export class PostService {
postsUrl: string = 'https://jsonplaceholder.typicode.com/posts';
constructor(private http: HttpClient) { }
removePost(post: Post | number): Observable<Post> {
const id = typeof post === 'number' ? post : post.id;
const url = `${this.postsUrl}/${id}`;
return this.http.delete<Post>(url, httpOptions);
}
I really do not understand this part:
removePost(post: Post | number): Observable<Post> {
const id = typeof post === 'number' ? post : post.id;
So far I have understood that the author is trying to extract the post.id so they can use it to assemble the return this.http.delete<Post>(url, httpOptions); and delete the record.
I do not understand how the above code works. Any ideas?