我对 AngularJS 比较陌生,我决定构建一个基本的博客应用程序来熟悉 MongoDB 并使用 $http 请求。
但是,我在使用 Angular 服务将用户在 $scope
上的表单中填写的数据发布到我的 MongoDB 数据库时遇到了一些麻烦。
最初,我将 $http 请求放入我的 Controller 中。这对我有用:
mainCtrl.js
$scope.addPost = function() {
$http.post('/api/blogs', $scope.formData)
.success(function(data) {
$scope.formData = {};
$location.path('blogs');
console.log(data, 'Blog created.');
})
.error(function(data) {
console.log('Error: ' + data);
})
};
但是这是通过我的 Controller 完成的,我知道这不是最佳实践,因此我尝试将此功能放入 Angular 服务中。
以下是构成应用程序这一部分的相关代码部分,包括 HTML View :
server.js
//Dependencies.
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var cors = require('cors');
var mongoose = require('mongoose');
var mongojs = require('mongojs');
var http = require('http');
var path = require('path');
var fs = require('fs');
var dotenv = require('dotenv');
var port = 9001;
var mongoUri = 'mongodb://localhost:27017/blog-app';
var app = express();
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
//Blog Data & Data Storage.
-----------------------------
var Schema = mongoose.Schema;
var blogSchema = new Schema({
title : {type: String, min: 8, max: 50, required: true},
body : {type: String, required: true},
author : {type: String, min: 3, max: 40, required: true},
pubdate : {type: Date, default: Date.now}
});
var Blog = mongoose.model('Blog', blogSchema);
//Routes.
----------
// GET BLOGS!
app.get('/api/blogs', function(req, res) {
Blog.find(function (err, blogs) {
if (err)
res.send(err);
res.json(blogs);
});
});
// POST BLOG!
app.post('/api/blogs', function(req, res) {
Blog.create({
title: req.body.title,
body: req.body.body,
author: req.body.author,
date: req.body.date
}, function(err, blog) {
if (err)
res.send(err);
Blog.find(function(err, blogs) {
if (err)
res.send(err);
res.json(blogs);
});
});
});
mainCtrl.js
var app = angular.module("blog-app");
app.controller('MainController', ['mainService', '$scope', '$http', '$location', '$stateParams', '$state', function(mainService, $scope, $http, $location, $stateParams, $state) {
$scope.formData = {};
$scope.blog = [];
function getBlogs() {
mainService.getPosts().then(function(data) {
$scope.blog = data;
console.log(data, "The blogs.");
});
}
getBlogs();
$scope.readPost = function(id) {
mainService.readPost(id).then(function(data) {
$scope.readblog = data;
console.log(data, "This is the blog you selected.")
});
};
$scope.addPost = function(formData) {
mainService.addPost(formData).then(function() {
$scope.formData = {};
$location.path('blogs');
console.log(data, 'Blog created.');
});
};
}]); //End Controller.
mainService.js
var app = angular.module("blog-app");
app.service('mainService', function($http, $q) {
var blog = [];
var readblog = {};
var formData = {};
this.getPosts = function() {
return $http.get('/api/blogs').then(function(response){
blog = response.data;
return blog;
});
}
this.readPost = function(id) {
return $http.get('/api/blogs/' + id).then(function(response) {
readblog = response.data;
return readblog;
});
};
this.addPost = function(formData) {
$http.post('/api/blogs', formData);
};
});
newblog.html
<div class="newblog">
<a ui-sref="blogs"><i class="fa fa-close fa-2x exit"></i></a>
<div class="form">
<form>
<i class="fa fa-pencil-square-o fa-5x"></i><br>
<input class="blogtitle" type="text" ng- model="formData.title" placeholder="Blog Title" required /><br>
<textarea ng-model="formData.body" rows="15" placeholder="Write the body of your blog here." required></textarea><br>
<label for="">by:</label><br>
<input class="blogauthor" type="text" ng-model="formData.author" placeholder="Author Name" required /><br><br>
<button type="submit" ng- click="addPost()">Submit</button>
</form>
</div>
</div>
所以...
...要明确的是,我希望能够使用 addPost()
函数单击 newblog.html 中的按钮,并将其放入我的数据库中的表单数据。我不清楚的是如何在我的服务中引用用户在 $scope
中输入的数据,以便我实际上可以将其发布到数据库,或者如果这可能的话。在 Controller 中执行此操作很容易(如帖子中的示例所示),但我想在服务中执行此操作。
我尝试过的:
服务功能
this.addPost = function(formData) {
$http.post('/api/blogs', formData).then(function(response) {
blog.push(response.data);
return blog;
})
};
然后...
Controller 功能
$scope.addPost = function(data) {
mainService.addPost(data).then(function(data) {
$scope.blog.push(data);
console.log(data, 'Blog created.');
});
};
我不记得我还尝试过什么,但最终没有效果。我猜这可能是一些非常简单的事情,我在谷歌搜索时可能忽略了。任何帮助将不胜感激,还将澄清任何不太有意义的事情。如果我发现任何问题,将继续努力并修复/回答问题。
最佳答案
您的 Controller 功能应该是:
$scope.addPost = function() {
mainService.addPost($scope.formData).then(function() {
$scope.formData = {};
$location.path('blogs');
console.log(data, 'Blog created.');
});
};
您没有从 View 中传递任何内容,因此本质上您是在使用 formData
的 null 值调用 mainService.addPost
。
更新
第一次阅读您的问题时我错过了这一点,但服务方法需要返回 promise :
this.addPost = function(formData) {
return $http.post('/api/blogs', formData);
};
关于javascript - 使用 Angular/Nodejs 将表单数据发布到 MongoDB 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37448825/