Stekosto
Stekosto

Reputation: 43

I am trying to understand this piece of TypeScript code

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?

Upvotes: 3

Views: 73

Answers (2)

John Montgomery
John Montgomery

Reputation: 7096

removePost(post: Post | number)

This is a function that takes one parameter. That parameter can be either a Post object or a simple number.

const id = typeof post === 'number' ? post : post.id;

This part decides how to determine the ID. Presumably, if the parameter is a number, that is the ID itself, while if you give it an object it has to get it from the object's properties, so it has to check the type to know which way to do it. If the ternary syntax confuses you, it can be roughly rewritten like this:

let id // changed to let because you can't declare a const without assigning it immediately
if (typeof post === 'number') {
    id = post
} else {
    id = post.id
}

Upvotes: 1

danday74
danday74

Reputation: 56936

Remove post is triggered by clicking on the <button (click)="removePost(post)" ...>

The removePost method in turn calls the postService.removePost which makes an HTTP request and returns an Observable of the response.

In that method ...

TypeScript allows you to define multiple types. So in this case post must be of type Post OR type number.

If the post is of type number then set the id to the number given. If it is of type Post then use the id property from the post object (post.id).

removePost(post: Post | number): Observable<Post> {
const id = typeof post === 'number' ? post : post.id;

Then finally, in the .subscribe() block back in the removePost method the HTTP response is received (but ignored). The function inside subscribe is called only on an HTTP success which means on the backend server the delete has taken place. So he does a splice to remove the post from the frontend data.

Upvotes: 3

Related Questions