我一直在尝试使用MEAN堆栈创建博客应用。我有问题将帖子呈现为HTML。在浏览器上,它只显示{{posts}}
HTML code:
<!DOCTYPE html>
<html lang="en" ng-app="BlogApp">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="app.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="container" ng-controller="BlogController">
<h1>Blog</h1>
<input ng-model="post.title" class="form-control" placeholder="title"/>
<textarea ng-model="post.body" class="form-control" placeholder="body"></textarea>
<button ng-click="createPost(post)" class="btn btn-primary btn-block">Post</button>
{{posts}}
</div>
</body>
</html>
角度代码:
(function() {
angular.module("BlogApp", []).controller("BlogController", BlogController);
function BlogController($scope, $http) {
$scope.createPost=createPost;
function init() {
getAllPosts();
}
init();
function getAllPosts() {
$http.get("/api/blogpost").success(function(posts) {
$scope.posts=posts;
});
}
function createPost(post) {
console.log(post);
$http.post("/api/blogpost", post);
}
}
})();
答案 0 :(得分:0)
由于您使用的是角度1.6.x,因此必须使用.then
和.catch
而不是.success
和.error
,因为后者在较新版本中已弃用。< / p>
(function() {
angular.module("BlogApp", []).controller("BlogController", BlogController);
function BlogController($scope, $http) {
$scope.createPost=createPost;
getAllPosts();
function getAllPosts() {
$http.get("/api/blogpost").then(function(response) {
$scope.posts=response.data; //check if this is what you are looking for
});
}
function createPost(post) {
console.log(post);
$http.post("/api/blogpost", post);
}
}
})();
答案 1 :(得分:0)
您的getAllPosts函数应使用 .then
而不是 .success
,因为.success不推荐使用1.3以上的角度版本
function getAllPosts() {
$http.get("/api/blogpost").then(function(response) {
$scope.posts=response.data;
});
}