2017-08-06 118 views
0

我已经创建了一个Angular应用程序,它允许用户对特定媒体文件(如视频)进行评论。发布评论时,会发起一个http POST调用,将评论存储在数据库中。订阅API调用:Angular2

加载组件时,ngOnInit通过发起http GET调用从数据库加载所有注释。但是,当发布新评论时,如果没有刷新页面,评论不会更新。他们是否可以在评论发布时更新评论列表而无需刷新页面?

回答

0

为了简单起见,让我们假设你有一个组件ViewComponent,显示的评论列表,以及评论表单添加新的评论。 ViewComponent具有public comments: Comment[]这样的注释的本地状态,该注释由您的ngOnInit()中的GET API调用初始化。

我假设你有一个服务,如CommentsService,使api调用。 当您添加评论时,将调用函数addComment(comment),该函数处理POST请求。当POST成功时,评论将添加到您的评论数组中。

如果服务返回可观察到的(这里没有退订):

addComment(comment: Comment): void { 
    this.commentService.add(comment) 
    .subscribe(comment => { 
     this.comments.push(comment); 
    }); 
} 

如果服务返回一个承诺:

addComment(comment: Comment): void { 
    this.commentService.add(comment) 
    .then(comment => { 
     this.comments.push(comment); 
    }); 
} 
2

subscribehttp.postsuccess发布后添加到您的帖子阵列this.posts.push(newPost)