
- MEAN.JS 教程
- MEAN.JS - 首頁
- MEAN.JS - 概述
- MEAN.JS - 架構
- 構建 Node Web 應用
- MEAN.JS - Mean 專案設定
- 構建靜態路由 Node Express
- MEAN.JS - 構建資料模型
- MEAN.JS - REST API
- 使用 Angular 構建前端
- 應用中的 Angular 元件
- 使用 Angular 構建單頁應用
- 構建單頁應用:進階篇
- MEAN.JS 有用資源
- MEAN.JS - 快速指南
- MEAN.JS - 有用資源
- MEAN.JS - 討論
MEAN.JS - 構建單頁應用:進階篇
在上一章中,我們學習瞭如何使用 AngularJS 建立 MEAN.JS 單頁應用程式。本章我們將學習 Angular 應用程式如何使用 API 從 MongoDB 獲取資料。
您可以從此連結下載此應用程式的原始碼。下載 zip 檔案;將其解壓到您的系統中。
我們的原始碼目錄結構如下:
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 檔案中。這是 Node 應用的主檔案,將配置整個應用程式。
// 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 https://:3000 app.listen(port, () ⇒ console.log(`Example app listening on port ${port}!`));
定義前端路由
public/index.html 檔案將包含以下程式碼片段:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <base href="/"> <title>Tutorialspoint Node and Angular</title> <!-- CSS --> <link rel="stylesheet" href="libs/bootstrap/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="css/style.css"> <!-- custom styles --> <!-- JS --> <script src="libs/angular/angular.min.js"></script> <script src="libs/angular-route/angular-route.min.js"></script> <!-- ANGULAR CUSTOM --> <script src="js/controllers/MainCtrl.js"></script> <script src="js/controllers/StudentCtrl.js"></script> <script src="js/services/StudentService.js"></script> <script src="js/appRoutes.js"></script> <script src="js/app.js"></script> </head> <body ng-app="sampleApp" ng-controller="MainController"> <div class="container"> <!-- HEADER --> <nav class="navbar navbar-inverse"> <div class="navbar-header"> <a class="navbar-brand" href="/">Tutorial</a> </div> <ul class="nav navbar-nav"> <li><a href="/students">Students</a></li> </ul> </nav> <!-- ANGULAR DYNAMIC CONTENT --> <div ng-view></div> </div> </body> </html>
我們編寫了一個服務來進行 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
現在導航到https://:3000,您將看到如下所示的頁面:

在文字框中輸入一些文字,然後單擊新增按鈕。將新增並顯示一條記錄,如下所示:

您可以透過選中複選框來刪除記錄。
廣告