【发布时间】:2017-12-30 09:49:49
【问题描述】:
我正在使用 MEAN 堆栈制作一个简单的博客,但遇到了一个简单的问题。
这是我用来检索所有帖子的 HTML 部分:
index.html:
<div ng-repeat="post in posts">
<h2>
{{post.title}}
<a ng-click="deletePost(post._id)"class="pull-right"><i class="fa fa-times" aria-hidden="true"></i></a>
</h2>
<em>{{post.posted}}</em>
<p>{{post.body}}</p>
</div>
请注意:<i class="fa fa-times" aria-hidden="true"></i> 是取自 FontAwesome 库的图标
这是我的 Angular 应用控制器:
(function () {
angular
.module("BlogApp", [])
.controller("BlogController", BlogController);
function BlogController($scope, $http) {
$scope.createPost = createPost;
$scope.deletePost = deletePost;
function init() {
getAllPosts();
}
init();
function deletePost(postId) {
$http.delete('/api/blogpost/' + postId).then(getAllPosts);
}
function getAllPosts() {
$http.get("/api/blogpost").then(function(posts){
$scope.posts = posts.data
});
}
这是我的服务器处理删除请求的部分:
// deletePost
app.delete('/api/blogpost/:id', deletePost);
function deletePost(req, res) {
var postId = req.params.id;
PostModel.remove({_id: postId}).then(
function() {
res.sendstatus(200);
},
function() {
res.sendStatus(400);
}
);
}
单击 X 图标时,该操作确实会命中我的控制器,到达服务器并设法从我的数据库中删除帖子,但由于某种原因,它不会使用我的所有帖子自动更新页面。我必须刷新它。这就是为什么我认为在访问服务器后立即在控制器中调用函数getAllPosts 会更新数据。我错过了什么?
【问题讨论】:
-
不应该是
$scope.post吗? -
好吧,我将标题和正文的模型添加为
ng-model="post.title",因此帖子是帖子对象的数组。老实说,我不知道写错了什么,但是我在服务器中重新编写了deletePost函数,现在它可以工作了。我认为这是猫鼬承诺的问题。老实说,我仍然觉得这很令人困惑。 -
那你应该回答你的问题接受并关闭它
标签: angularjs node.js mongodb mean-stack