【发布时间】:2019-02-25 06:49:19
【问题描述】:
我有这个模板显示这些帖子:
<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);并删除记录。
我不明白上面的代码是如何工作的。有什么想法吗?
【问题讨论】:
-
你到底有什么不明白的? conditional operator?
-
您可以通过两种方式调用 removePost,
removePost(post)(其中 post 是 Post 对象)和removePost(35)(其中 35 是帖子的 id)。通过该行,作者试图了解参数是什么类型,并据此使用 id 或从对象中提取 id -
@danday74 @John @Cristian 因此,如果传递的是整个对象,而不是数字,则使用 post.id 但如果传递了数字,那么这就是 id 本身,因此请按原样使用 post。因此,如果它是 `
标签: javascript arrays angular typescript observable