📅  最后修改于: 2020-10-22 05:25:43             🧑  作者: Mango
在上一章中,我们已经看到了使用Angularjs创建单页meanjs应用程序的过程。在本章中,让我们看看Angular应用程序如何使用API从Mongodb中获取数据。
您可以在此链接中下载此应用程序的源代码。下载压缩文件;将其提取到您的系统中。
我们的源代码的目录结构如下-
mean-demo
-app
-models
-student.js
-config
-db.js
-public
-js
-controllers
-MainCtrl.js
-StudentCtrl.js
-services
-StudentService.js
-app.js
-appRoutes.js
-views
-home.html
-student.html
-index.html
-.bowerrc
-bower.json
-package.json
-server.js
在此应用程序中,我们创建了一个视图(home.html),该视图将列出集合Student中的所有学生,允许我们创建新的学生记录,并允许我们删除学生记录。所有这些操作都是通过REST API调用执行的。
打开终端并运行以下命令以安装npm模块依赖项。
$ npm install
接下来,使用以下命令安装Bower组件。您可以看到bower提取了public / libs下的所有文件。
$ bower install
应用程序的节点配置将保存在server.js文件中。这是节点应用程序的主文件,将配置整个应用程序。
// modules =================================================
const express = require('express');
const app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var methodOverride = require('method-override');
// set our port
const port = 3000;
// configuration ===========================================
// configure body parser
app.use(bodyParser.json()); // parse application/json
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// override with the X-HTTP-Method-Override header in the request.
app.use(methodOverride('X-HTTP-Method-Override')); simulate DELETE/PUT
// set the static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public'));
// config files
var db = require('./config/db');
console.log("connecting--",db);
mongoose.connect(db.url); //Mongoose connection created
// grab the student model
var Student = require('./app/models/student');
function getStudents(res) {
Student.find(function (err, students) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err) {
res.send(err);
}
res.json(students); // return all todos in JSON format
});
};
app.get('/api/studentslist', function(req, res) {
getStudents(res);
});
app.post('/api/students/send', function (req, res) {
var student = new Student(); // create a new instance of the student model
student.name = req.body.name; // set the student name (comes from the request)
student.save(function(err) {
if (err)
res.send(err);
getStudents(res);
});
});
app.delete('/api/students/:student_id', function (req, res) {
Student.remove({
_id: req.params.student_id
}, function(err, bear) {
if (err)
res.send(err);
getStudents(res);
});
});
// startup our app at http://localhost:3000
app.listen(port, () ⇒ console.log(`Example app listening on port ${port}!`));
public / index.html文件将具有以下代码片段-
Tutorialspoint Node and Angular
我们编写了一项服务,以进行API调用并执行API请求。我们的服务StudentService如下所示-
angular.module('StudentService', [])
// super simple service
// each function returns a promise object
.factory('Student', ['$http',function($http) {
return {
get : function() {
return $http.get('/api/students');
},
create : function(student) {
return $http.post('/api/students/send', student);
},
delete : function(id) {
return $http.delete('/api/students/' + id);
}
}
}]);
我们的控制器(MainCtrl.js)代码如下-
angular.module('MainCtrl', []).controller('MainController',
['$scope','$http','Student',function($scope, $http, Student) {
$scope.formData = {};
$scope.loading = true;
$http.get('/api/studentslist').
then(function(response) {
$scope.student = response.data;
});
// CREATE
// when submitting the add form, send the text to the node API
$scope.createStudent = function() {
// validate the formData to make sure that something is there
// if form is empty, nothing will happen
if ($scope.formData.name != undefined) {
$scope.loading = true;
// call the create function from our service (returns a promise object)
Student.create($scope.formData)
// if successful creation, call our get function to get all the new Student
.then(function (response){
$scope.student = response.data;
$scope.loading = false;
$scope.formData = {}
}, function (error){
});
}
};
// DELETE
==================================================================
// delete a todo after checking it
$scope.deleteStudent = function(id) {
$scope.loading = true;
Student.delete(id)
// if successful delete, call our get function to get all the new Student
.then(function(response) {
$scope.loading = false;
new list of Student
});
};
}]);
导航到您的项目目录并运行下面给出的命令-
$ npm start
现在导航到http:// localhost:3000 ,您将获得下图所示的页面-
在文本框中输入一些文本,然后单击“添加”按钮。一条记录被添加并显示如下-
您可以通过选中复选框来删除记录。