[英]I am trying to understand this piece of TypeScript code
我有这个模板显示这些帖子:
<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>
remove函数使用名为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 OR类型编号。
如果帖子的类型编号,则将id设置为给定的数字。 如果它是Post类型,则使用post对象的id属性( post.id
)。
removePost(post: Post | number): Observable<Post> {
const id = typeof post === 'number' ? post : post.id;
最后,在removePost方法中的.subscribe()块中,接收到HTTP响应(但忽略)。 subscribe内部的函数仅在HTTP成功时调用,这意味着在后端服务器上发生了删除。 所以他做了一个拼接来从前端数据中删除帖子。
removePost(post: Post | number)
这是一个带一个参数的函数。 该参数可以是Post
对象或简单数字。
const id = typeof post === 'number' ? post : post.id;
这部分决定了如何确定ID。 据推测,如果参数是一个数字,那就是ID本身,而如果你给它一个对象,它必须从对象的属性中获取它,所以它必须检查类型以知道这样做的方式。 如果三元语法混淆了你,可以大致重写如下:
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.