使用Angular / Nodejs将表单数据发布到MongoDB数据库

我对AngularJS比较陌生,我决定构build一个基本的博客应用程序,以熟悉MongoDB并使用$ http请求。

不过,使用我的Angular服务将用户填充到$scope的表单中的数据发布到我的MongoDB数据库时遇到了一些麻烦。

最初,我把$ http请求放在我的控制器中。 这适用于我:

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); }) }; 

但是这是通过我的控制器完成的,而且我明白这不是最佳实践,所以我试图将这个function放在一个Angular服务中。

以下是构成应用程序的这部分代码的相关部分,包括HTML视图:

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中的button,并将表单数据放到我的数据库中。 我不清楚的是如何引用用户在$scopeinput的数据,在我的服务中,所以我实际上可以将其发布到数据库,或者甚至可能。 在控制器中很容易做到这一点(在例子中显示),但我想在服务中做到这一点。

我曾尝试过:

服务function

 this.addPost = function(formData) { $http.post('/api/blogs', formData).then(function(response) { blog.push(response.data); return blog; }) }; 

接着…

控制器function

 $scope.addPost = function(data) { mainService.addPost(data).then(function(data) { $scope.blog.push(data); console.log(data, 'Blog created.'); }); }; 

我不记得我还试过了什么,但最终却无济于事。 我猜测这可能是一些非常简单的事情,我可能在我的Googlesearch任务中被忽视。 任何帮助将不胜感激,也将阐明任何不太合理的事情。 如果我find任何东西,将继续工作,并修复/回答问题。

你的控制器function应该是:

 $scope.addPost = function() { mainService.addPost($scope.formData).then(function() { $scope.formData = {}; $location.path('blogs'); console.log(data, 'Blog created.'); }); }; 

你没有从视图中传递任何东西,所以你基本上是用mainService.addPost的null值调用formData

更新

当我第一次读你的问题时,我错过了这个,但是服务方法需要返回这个诺言:

 this.addPost = function(formData) { return $http.post('/api/blogs', formData); };