首页 > 解决方案 > 我试图理解这段 TypeScript 代码

问题描述

我有这个模板显示这些帖子:

<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>

删除功能使用名为 servicePost 的服务来删除帖子

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);
          }
        });
      });
    }
  }

以及服务本身

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);  
      }

我真的不明白这部分:

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

到目前为止,我了解到作者正在尝试提取 ,post.id以便他们可以使用它来组装return this.http.delete<Post>(url, httpOptions);和删除记录。

我不明白上面的代码是如何工作的。有任何想法吗?

标签: javascriptarraysangulartypescriptobservable

解决方案


删除帖子是通过点击触发的<button (click)="removePost(post)" ...>

removePost 方法依次调用postService.removePost发出 HTTP 请求并返回响应的 Observable。

在那种方法...

TypeScript 允许您定义多种类型。所以在这种情况下,post 必须是 Post OR type number 类型。

如果帖子是数字类型,则将 id 设置为给定的数字。如果它是 Post 类型,则使用 post 对象 ( post.id) 中的 id 属性。

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

最后,在 removePost 方法的 .subscribe() 块中,接收到 HTTP 响应(但被忽略)。subscribe 内部的函数仅在 HTTP 成功时调用,这意味着在后端服务器上已发生删除。所以他做了一个拼接来从前端数据中删除帖子。


推荐阅读