javascript - 我试图理解这段 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);
和删除记录。
我不明白上面的代码是如何工作的。有任何想法吗?
解决方案
删除帖子是通过点击触发的<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 成功时调用,这意味着在后端服务器上已发生删除。所以他做了一个拼接来从前端数据中删除帖子。
推荐阅读
- flutter - 如何创建日历颤动
- arcore - 谷歌 AR 支持小米 POCO X3 Pro
- ios - 有没有办法将 Swift 枚举类型的变量分配给 NSObject 类型的变量?
- python - 根据 Python 中另一个数组的顺序对一个数组进行排序
- flutter - 无法通过终端运行颤振升级
- pyomo - WinPython 3940 上的 Pyomo 6.0:安装 Ipopt 的最佳方式?
- javascript - 我可以从 cli 将 npm 脚本添加到 package.json 文件吗?
- android - android cmake 错误使用 2 字节 wchar_t 但输出是使用 4 字节
- java - HikariCP总是使用mysql root?
- python - 为什么我写了“epoch”之后程序总是崩溃,即使我正在学习教程?