帖子删除仅在刷新后发生-刷新并删除帖子后激活订阅

时间:2019-09-08 06:16:41

标签: angular typescript

我正在关注一些课程。因此,我得到了delete函数的作用,直到将其从节点服务器中删除为止。这是一个具有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' });
      });
    });

我该如何解决?

也许出于某种原因不允许立即删除-添加,删除后立即删除-是这样吗?

2 个答案:

答案 0 :(得分:0)

您需要使用onDelete方法而非服务来订阅服务。 在服务中,将http删除请求作为Observable返回。

以下是一些需要理解的代码: 服务中的DeletePost方法

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

这将删除后端上的帖子,并通过console.log通知您。然后,您可以更新本地的Post变量

您可以在http://reactivex.io/

上了解更多有关Observables和Subscription的信息。

答案 1 :(得分:0)

好的,所以这实际上是帖子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]);
      });