博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
angular删除节点_节点和Angular To-Do应用程序:应用程序的组织和结构
阅读量:2509 次
发布时间:2019-05-11

本文共 16747 字,大约阅读时间需要 55 分钟。

angular删除节点

This article will look into best practices for laying out and organizing a Node and Angular (MEAN stack) app.

本文将研究用于布局和组织Node and Angular(MEAN堆栈)应用程序的最佳实践。

This article has been updated for
本文已针对 . 更新。

In the process of extending our Node and Angular To-Do App with authorization, I ran into a problem: the tutorial was going to be huge. In our first tutorial, we placed everything (variables, configuration, models, routes, and more) in our server.js file. While this is fine for demonstration purposes and small Node applications, it wasn't going to work with how far we wanted to take this To-Do app.

在使用授权扩展我们的Node和Angular To-Do App的过程中,我遇到了一个问题:本教程将非常庞大。 在我们的第一个教程中,我们将所有内容(变量,配置,模型,路由等)放置在server.js文件中。 尽管这对于演示目的和小型Node应用程序来说是很好的选择,但它与我们想要将此To-Do应用程序带走的距离无关。

Demo: The demo will be the same as the first demo. The underlying code will be different however.
演示:该演示将与第一个演示相同。 但是,基础代码将有所不同。

应用结构 (Application Structure)

The structure of the files in our application is very important. It can help us expand and grow the app as we will inevitably get more and more popular (hopefully), or it could make coming back to the code an absolute nightmare.

我们应用程序中文件的结构非常重要。 它可以帮助我们扩展和增长该应用程序,因为我们不可避免地会越来越受欢迎(希望如此),或者它可能会使重新回到代码中成为绝对的噩梦。

There are so many different ways to lay out a MEAN (MongoDB, Express, Angular, Node) app, and the tutorials online show that. This tries to lean close to best practices and the best ideas taken from many of those MEAN stack tutorials.

布置MEAN(MongoDB,Express,Angular,Node)应用的方法有很多,在线教程显示了这一点。 这试图从许多MEAN堆栈教程中汲取最佳实践和最佳思想。

In this article, we'll look at how we can separate the core functions of our app into a sensible and sane file structure. Let's begin.

在本文中,我们将研究如何将应用程序的核心功能分离为明智而合理的文件结构。 让我们开始。

我们目前的应用 (Our Current Application)

Since this is an extension of our first article, we will be using the same code. If you haven't done so already, that code so you can follow along, or if you have a ton of RAM in that brain of yours (or good memory), just read on through.

由于这是我们第一篇文章的扩展,因此我们将使用相同的代码。 如果还没有这样做,请该代码以便您继续学习,或者如果您的大脑中有大量的RAM(或良好的内存),则请通读。

The code from the first article isn't really necessary if you don't want to pull it down. The concepts still apply to any MEAN application.

如果您不想删除第一篇文章中的代码,那么它实际上不是必需的。 这些概念仍然适用于任何MEAN应用程序。

Our application stores all functionality in server.js. Here is our current file structure:

我们的应用程序将所有功能存储在server.js中 。 这是我们当前的文件结构:

- public
----- core.js
----- index.html
- package.json
- server.js

Here is our server.js. Super long and could get confusing to read through in the future.

这是我们的server.js。 太长了,将来可能会混淆阅读。

// set up ======================================================================var express = require('express');var app = express(); // create our app w/ expressvar mongoose = require('mongoose'); // mongoose for mongodbvar morgan = require('morgan'); // log requests to the console (express4)var bodyParser = require('body-parser'); // pull information from HTML POST (express4)var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)var port = process.env.PORT || 8080;// configuration ===============================================================mongoose.connect('mongodb://node:node@mongo.onmodulus.net:27017/uwO3mypu'); // connect to mongoDB database on modulus.ioapp.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for usersapp.use(morgan('dev')); // log every request to the consoleapp.use(bodyParser.urlencoded({'extended':'true'})); // parse application/x-www-form-urlencodedapp.use(bodyParser.json()); // parse application/jsonapp.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as jsonapp.use(methodOverride());// define model ================================================================var Todo = mongoose.model('Todo', { text : String, done : Boolean});// routes ====================================================================== // api --------------------------------------------------------------------- // get all todos app.get('/api/todos', function(req, res) { ... }); // create todo and send back all todos after creation app.post('/api/todos', function(req, res) { ... }); // delete a todo app.delete('/api/todos/:todo_id', function(req, res) { ... }); // application ------------------------------------------------------------- app.get('*', function(req, res) { res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end) });// listen (start app with node server.js) ======================================app.listen(port);console.log("App listening on port " + port);

This single file approach is obviously not idea for expanding our app.

单一文件方法显然不是扩展我们的应用程序的主意。

向前进 (Moving Forward)

In the future, we want our app to-do cool things like:

将来,我们希望我们的应用执行以下类似的出色操作:

  • Creating more models

    创建更多模型
  • Have custom configs

    有自定义配置
  • Authentication using Passport for local, Facebook, and Google

    使用Passport对本地,Facebook和Google进行身份验证
  • Real time updating with Socket.io

    使用Socket.io实时更新
  • and so much more...

    还有更多...

In order for that to happen, we will need to move some parts around so that each section is extendable. We want flexibility to add more models, config options, features, routes, and whatever else easily.

为了做到这一点,我们将需要移动一些部件,以便每个部分都可扩展。 我们希望可以灵活地添加更多模型,配置选项,功能,路线以及其他任何内容。

新文件结构 (New File Structure)

We will show off an overview of what our site structure will move to and then go through each part and explain it. Our app will function the same as before, it will just be better set up for the future.

我们将展示我们的网站结构将要到达的概述,然后遍历每个部分并对其进行解释。 我们的应用程序的功能将与以前相同 ,因此将来会更好。

- app
----- models ---------- todo.js
----- routes.js
- config
----- database.js - public
----- core.js
----- index.html
- package.json
- server.js

This file structure took a lot of inspiration from and . Those both have a more complex file structure and inner workings. This will be much simpler to show off the basic concepts of file separation.

该文件结构从和获得了很多启发。 两者都具有更复杂的文件结构和内部工作原理。 这将更容易展示文件分离的基本概念。

配置,模型和路由 (Config, Models, and Routes)

Our old application had everything in server.js. You can imagine how large this one file would become. We'll go through that file and move everything out one by one.

我们的旧应用程序包含server.js所有内容。 您可以想象这个文件将变成多大。 我们将遍历该文件并将所有内容逐一移出。

数据库配置config / database.js (Database Config config/database.js)

Connecting to our database is currently handled in server.js in the configuration section.

当前在配置部分的server.js中处理连接到我们的数据库的问题。

// server.js (old)...    mongoose.connect('mongodb://node:node@mongo.onmodulus.net:27017/uwO3mypu');     // connect to mongoDB database on modulus.io...

Let's separate out the URL for connecting to the database into our config/database.js.

让我们将用于连接数据库的URL分离到config / database.js中

// config/database.js    module.exports = {        url : 'mongodb://node:node@mongo.onmodulus.net:27017/uwO3mypu'    };

Now in our server.js, we can pull that database config.

现在在server.js ,我们可以提取该数据库配置。

// server.js (new)    // load the config    var database = require('./config/database');    mongoose.connect(database.url);     // connect to mongoDB database on modulus.io

Why do this? I know it seems a little useless since it's only the one configuration setting. It will pay off in the future though when we have multiple settings across multiple files (auth, database, application, environment).

为什么这样 我知道这似乎没什么用,因为它只是一个配置设置。 当我们对多个文件(身份验证,数据库,应用程序,环境)进行多项设置时,它将在将来获得回报。

Understanding module.exports: module.exports allows you to pass data from one file to another. Just using
require('./config/database') doesn't automagically give you access to those variables. module.exports exposes those variables (or functions or anything else) to other files. For a more thorough understanding, there's this by Karl Seguin.
了解module.exports: module.exports允许您将数据从一个文件传递到另一个文件。 仅使用
require('./config/database')并不能自动访问这些变量。 module.exports将那些变量(或函数或其他任何东西)公开给其他文件。 为了更深入地了解,Karl Seguin 了这篇 。

There are many different ways to use module.exports, and we'll be sure to write up an article in the future for all the ways to use it. Now that our config is separated out, we'll move onto the models.

使用module.exports的方式有很多,我们一定会在以后为使用它的所有方式写一篇文章。 现在我们的配置已分离出来,我们将继续进行模型。

模型app / models / todo.js (Model app/models/todo.js)

Here is our old code for the todo model in our giant server.js.

这是我们巨型server.js todo模型的旧代码。

// server.js (old)...    // define model ================================================================    var Todo = mongoose.model('Todo', {        text : String,        done : Boolean    });...

We'll move our current models entirely out of server.js. In our new app/models/todo.js, let's use module.exports and expose our Todo mongoose model to the file that needs it whenever it is loaded using require.

我们将当前模型完全移出server.js 。 在我们新的app / models / todo.js中 ,让我们使用module.exports,并在使用require加载时将Todo猫鼬模型暴露给需要它的文件。

// app/models/todo.js    // load mongoose since we need it to define a model    var mongoose = require('mongoose');    module.exports = mongoose.model('Todo', {        text : String,        done : Boolean    });

Since this model is used by our routes in server.js, and we are moving the routes out of server.js into app/routes.js, we won't need to load the model there. We will load this model in the app/routes.js file. Just remove the lines for defining the model in server.js.

由于此模型由server.js路由使用,并且我们将路由从server.js中移出至app/routes.js ,因此无需在此处加载模型。 我们将在app / routes.js文件中加载此模型 。 只需删除server.js中用于定义模型的行即可。

With models out of the main server.js file, our file is that much cleaner. The bulk of the code is the routes however and we'll get that separated out next.

由于模型不在主要的server.js文件中,因此我们的文件更加整洁。 代码的大部分是路由,但是我们接下来将其分离出来。

路由app / routes.js (Routes app/routes.js)

We are going to move all of the routes in server.js out to the app/routes.js file. I personally prefer to hold all routes in a single file. This let's me see a top down view of my entire application without having to dig through other files. If any of my routes start getting overly code heavy, I'll move that code into a controller and load the controller in the routes.

我们将把server.js所有路由移到app / routes.js文件中。 我个人更喜欢将所有路由保存在一个文件中。 这让我看到了整个应用程序的俯视图,而无需浏览其他文件。 如果我的路线中的任何一条开始变得代码过多,我将把这些代码移到控制器中并将控制器加载到路线中。

Of course, this is up to your own preference to separate routes into separate files or into controllers. Some people like to separate the different routes into different files (ie api, auth, application).

当然,这取决于您自己的喜好,可以将路由分为单独的文件或控制器。 有些人喜欢将不同的路由分成不同的文件(即api,auth,application)。

Here's our old code that we'll move out of server.js.

这是我们将移出server.js的旧代码。

// server.js (old)// this file condensed since there's so much code...// routes ======================================================================    // api ---------------------------------------------------------------------    // get all todos    app.get('/api/todos', function(req, res) {        ...    });    // create todo and send back all todos after creation    app.post('/api/todos', function(req, res) {        ...    });    // delete a todo    app.delete('/api/todos/:todo_id', function(req, res) {        ...    });    // application -------------------------------------------------------------    app.get('*', function(req, res) {        res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)    });...

Move all of that code out of server.js and let' go over to our app/routes.js file.

将所有代码移出server.js然后转到我们的app/routes.js文件。

We will load our todo model, and use module.exports to expose the routes to our app.

我们将加载我们的todo模型 ,并使用module.exports 将路由公开给我们的应用程序

// app/routes.js// load the todo modelvar Todo = require('./models/todo');// expose the routes to our app with module.exportsmodule.exports = function(app) {    // api ---------------------------------------------------------------------    // get all todos    app.get('/api/todos', function(req, res) {        ...    });    // create todo and send back all todos after creation    app.post('/api/todos', function(req, res) {        ...    });    // delete a todo    app.delete('/api/todos/:todo_id', function(req, res) {        ...    });    // application -------------------------------------------------------------    app.get('*', function(req, res) {        res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)    });};

Now that we've defined our routes file, we'll just load that in our server.js and pass in our app variable to the function. This way the routes file has access to app and express. Now the routes we have defined are accessible in our server.js file thanks to module.exports.

现在,我们已经定义了路由文件,我们将其加载到server.js ,并将app变量传递给该函数。 这样,路由文件就可以访问appexpress 。 现在,借助module.exports,可以在server.js文件中访问我们定义的路由。

// server.js...    // load the routes    require('./app/routes')(app);...

That's it for the routes. That's it for everything actually.

路线就是这样。 实际上就是所有这些。

干净的应用程序,干净的头脑 (Clean App, Clean Mind)

Look at how clean our server.js is now.

看看我们的server.js现在有多干净。

// server.js (final)    // set up ======================================================================    var express  = require('express');    var app      = express();                               // create our app w/ express    var mongoose = require('mongoose');                     // mongoose for mongodb    var port     = process.env.PORT || 8080;                // set the port    var database = require('./config/database');            // load the database config        var morgan = require('morgan');             // log requests to the console (express4)    var bodyParser = require('body-parser');    // pull information from HTML POST (express4)    var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)    // configuration ===============================================================    mongoose.connect(database.url);     // connect to mongoDB database on modulus.io    app.use(express.static(__dirname + '/public'));                 // set the static files location /public/img will be /img for users    app.use(morgan('dev'));                                         // log every request to the console    app.use(bodyParser.urlencoded({'extended':'true'}));            // parse application/x-www-form-urlencoded    app.use(bodyParser.json());                                     // parse application/json    app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json    app.use(methodOverride());    // routes ======================================================================    require('./app/routes.js')(app);    // listen (start app with node server.js) ======================================    app.listen(port);    console.log("App listening on port " + port);

Compare that to the giant monster it used to be. That might be a bit of an exaggeration, but still, cleaner is better. Now we've moved configuration, models, and routes into their own separate files. Separation never felt so good.

将其与过去的巨型怪物进行比较。 可能有点夸张,但清洁工更好。 现在,我们将configurationmodelroute移到了自己的单独文件中。 分离从未如此美好。

Notice how everything in our public folder didn't have to change. Our Angular side of our application, the frontend, didn't have to change one bit. The separation of duties we established in our first app holds strong here. Node is the API level backend and Angular is the separate frontend.

请注意,公用文件夹中的所有内容都不必更改。 我们的应用程序的Angular端,即前端,不必更改一点。 我们在第一个应用程序中建立的职责分离在这里很重要。 Node是API级别的后端,而Angular是单独的前端。

If anyone has any suggestions, I'd be happy to hear them. I'm still on the long search for best practices in all things MEAN stack so any improvements are welcome.

如果有人有任何建议,我很乐意听到。 我仍在长期寻求MEAN堆栈中所有方面的最佳实践,因此欢迎进行任何改进。

向前进 (Moving Forward)

Stay on the lookout for the next articles in this series. We'll be going over Authentication with Passport next. We'll be able to authenticate our users locally, with Facebook, or using Google.

请继续关注本系列的下一篇文章。 接下来,我们将介绍使用Passport进行身份验证。 我们将能够使用Facebook或Google在本地对我们的用户进行身份验证。

series. 系列的一部分。
  1. Node Application Organization and Structure

    节点应用程序的组织和结构

翻译自:

angular删除节点

转载地址:http://onywd.baihongyu.com/

你可能感兴趣的文章
C# MySql 连接
查看>>
网络抓包分析方法大全
查看>>
sql 数据类型
查看>>
android 截图
查看>>
WebServicer接口类生成方法。
查看>>
POJ 1740
查看>>
【翻译】火影忍者鸣人 疾风传 终级风暴2 制作介绍
查看>>
http和webservice
查看>>
hdu1879------------prim算法模板
查看>>
jdbc之二:DAO模式
查看>>
MySQL性能优化方法一:缓存参数优化
查看>>
Angular2 - 概述
查看>>
正则表达式tab表示\t
查看>>
NodeJS+Express+MongoDB 简单实现数据录入及回显展示【Study笔记】
查看>>
Highcharts使用指南
查看>>
网络基础(子网划分)
查看>>
Google C++ Style
查看>>
MyBatis总结八:缓存介绍(一级缓存,二级缓存)
查看>>
div+css教程网站建设门户网站和电子商务网站CSS样式表
查看>>
[LeetCode][JavaScript]Candy
查看>>