gpt4 book ai didi

javascript - 迭代 Angular2 中的 Mongoose 帖子

转载 作者:太空宇宙 更新时间:2023-11-04 01:59:57 24 4
gpt4 key购买 nike

所以我是 Angular 的新手,尝试制作一个简单的博客网站,其中包含保存到 Mongoose 的 titlepost 。我想迭代数据库中的每个帖子以显示它们。我读到语法从 ng-repeat 更改为 ngFor & 我这样做了,但它显示的只是 json 形式的数据库条目。我在这里遗漏了什么吗?

index.html

<!DOCTYPE html>

<html lang ="en" ng-app="BlogApp">
<head>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<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">
<title>This is a title</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>

<div *ngFor = "let post of posts">
<h2> {{post.title}} </h2>
<em> {{post.posted}} </em>
<p> {{post.body}} </p>
{{post}}

</div>

{{posts}}

</div
</body>
</html>

server.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/blogfall2017', { useMongoClient: true });

var PostSchema = mongoose.Schema({
title: {type:String, required: true},
body: String,
tag: {type: String, enum: ['POLITICS', 'ECONOMY', 'EDUCATION']},
posted: {type:Date, default: Date.now}
}, {collection: 'post'});

var PostModel = mongoose.model("PostModel", PostSchema);

app.use(express.static( 'dirname' + '/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true}));

app.post("/api/blogpost", createPost);
app.get("/api/blogpost", getAllPosts);
function getAllPosts(req, res) {
PostModel
.find()
.then(
function(posts) {
res.json(posts);
},
function (err) {
res.sendStatus(400);
}
);
}



function createPost(req, res) {
var post = req.body;
console.log(post);
PostModel
.create(post)
.then(
function (postObj) {
res.json(200);
},
function (error) {
res.sendStatus(400);
}
);
}

app.listen(3000);

app.js

(function () {
angular
.module("BlogApp", [])
.controller("BlogController", BlogController);

function BlogController($scope, $http) {
$scope.createPost = createPost;

function init() {
getAllPosts();
}
init();

function getAllPosts() {
$http
.get("/api/blogpost")
.then(function(posts) {
$scope.posts = posts;
});
}

function createPost(post) {
console.log(post);
$http
.post("/api/blogpost", post)
.success(getAllPosts)
}
}
})();

最佳答案

<div ng-repeat="post in posts">...</div>

因为您使用的是 Angular 1.6.4。

关于javascript - 迭代 Angular2 中的 Mongoose 帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46385048/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com