Angular - 发表评论到数据库
问题描述:
我想从输入表单发表评论到我的数据库。我目前传递的评论为未定义的评论。该服务不记录,我得到一个500服务器错误:user_id违反不空null约束。我做错了什么?Angular - 发表评论到数据库
HTML(更新)
<div ng-controller="CommentsCtrl as commentsCtrl">
<div ng-show="makeComment" class="collapsible-header">
<input ng-model="comment" type="text" name="comment" id="comment_content" class="col s11 m11 l11" placeholder="Make a comment.">
<a href="" type="submit" class="col s1 m1 l1 black-text comment" ng-click="commentsCtrl.createComment(comment, userId, postId)"><i class="material-icons">check_circle</i></a>
</div>
控制器 - CommentsCtrl(更新)
this.comment = '';
createComment(comment, userId, postId) {
return this.commentsService.createComment(comment, userId, postId);
}
}
服务 - CommentsService(更新)
this.createcomment = $http;
this.commentContent = '';
this.postId;
this.userId;
createComment(comment, userId, postId) {
this.createcomment.post('/comments', { comment: this.commentContent, userId: this.userId, postId: this.postId })
.then((res) => {
this.comment = res.data;
})
.catch((err) => {
return err;
});
}
答
您没有传递任何值,用户id或postId:
this.commentsService.createComment(comment);
它们为空。
为什么'JSON.stringify' POST数据?只需传递一个json对象('this.createcomment.post('/ comments',{comment:commentContent,user_id:userId,post_id:postId})',并且在服务器上params可以作为'comment','user_id'和'post_id') –
哦,你需要像这样保存对'this'的引用:'var self = this;'并且在承诺解析/拒绝函数中,你需要使用'self.comment = res.data;' –
谢谢,我现在控制器正在工作。我可以记录评论并看到它被传递给服务。但是该服务仅记录:comment undefined undefined。所以userId和postId没有定义。如果我的服务是构造函数对象,那么定义它们的正确方法是什么? – TYPOI