我正在学习一些课程。所以我让删除功能工作到它从节点服务器中删除它的程度。这是一个带有mongodb数据库的Angular前端。
角度服务中的删除帖子:
deletePost(postId: string) {
this.http
.delete('http://localhost:3000/api/posts/' + postId)
.subscribe(() => {
console.log('deleted');
const updatedPosts = this.posts.filter(post => post.id !==
postId);
this.posts = updatedPosts;
this.postsUpdated.next([...this.posts]);
});
}
棱角分明的前端:
onDelete(postId: string) {
console.log('deleted');
this.postsService.deletePost(postId);
发生的情况是(注意控制台日志(,当您第一次单击前端中的删除控制台日志时,会触发。但没有删除。刷新页面并重试后,将触发服务的第二个删除控制台输出并删除帖子。
节点函数:
app.delete('/api/posts/:id', (req, res, next) => {
Post.deleteOne({ _id: req.params.id }).then(result => {
res.status(200).json({ message: 'Post deleted' });
});
});
我该如何解决这个问题?
也许由于某种原因不允许立即删除 - 添加,删除 - 是这样吗?
您需要在 onDelete 方法中订阅该服务,而不是在服务中订阅服务。 在服务中,将 http 删除请求作为可观察量返回。
以下是一些需要理解的代码: 服务中的删除发布方法
deletePost(postId: string) :Observable<any> {
return this.http.delete('http://localhost:3000/api/posts/' + postId);
}
在组件 .ts 文件中:
onDelete(postId: string) {
this.postsService.deletePost(postId).subscribe(()=>{
console.log("deleted");
});
}
这将删除后端上的帖子,并在通过控制台删除帖子时通知您.log。然后,您可以更新本地发布变量
您可以在 http://reactivex.io/了解有关可观察量和订阅的更多信息
好的,所以这真的是帖子ID问题 - 我是如何分心并忘记了什么的。但是 ID 必须从添加发布请求中的节点返回(摘录(:
post
.save()
.then(addedPost => {
console.log(addedPost + 'ADD');
res.status(201).json({
message: 'Post Added',
postId: addedPost._id
});
})
然后,该服务如下所示(摘录(:
.subscribe(responseData => {
console.log(responseData.message);
post.id = responseData.postId;
this.posts.push(post);
this.postsUpdated.next([...this.posts]);
});