[nodejs,mongodb,angularjs2]我的便利貼-web應用練習

来源:http://www.cnblogs.com/wangxinsheng/archive/2017/01/21/6337589.html
-Advertisement-
Play Games

1.目的:學習nodejs連接使用mongodb,用angularjs2展示數據 2.使用技術: 資料庫: mongodb 後端數據獲取: nodejs 前端數據展示: angularjs2 ...


1.目的:學習nodejs連接使用mongodb,用angularjs2展示數據
2.使用技術:
資料庫: mongodb
後端數據獲取: nodejs
前端數據展示: angularjs2
3.應用:
純mongodb CURD操作: http://127.0.0.1:3000/mongodb/
便利貼應用:http://127.0.0.1:3000/
4.運行方法:
1) 安裝有nodejs,mongodb
2) npm install supervisor -g
3) npm install
4) npm start
5.便利貼畫面樣式 參照http://jingyan.baidu.com/article/e75057f287c8abebc91a89d7.html
copyright:WangXinsheng
cnblogs.com/wangxinsheng

============================

http://127.0.0.1:3000/:

 

http://127.0.0.1:3000/mongodb/:

核心代碼:

1.mongodb操作用,使用mongodb驅動[nodejs]:

  1 // insert method
  2 var insertDocuments = function(db,data,col,callback) {
  3     // Get the documents collection
  4     var collection = db.collection(col);
  5     // Insert some documents
  6     collection.insertMany([data], function(err, result) {
  7         assert.equal(err, null);
  8         callback(result);
  9     });
 10 }
 11 // find documents
 12 var findDocuments = function(db,col,callback,filterJson={}) {
 13     // Get the documents collection
 14     var collection = db.collection(col);
 15     // Find some documents
 16     collection.find(filterJson).toArray(function(err, docs) {
 17         assert.equal(err, null);
 18         docs.sort(function(a,b){return b.time.replace(/\-/g,'') - a.time.replace(/\-/g,'');});
 19         callback(docs);
 20     });
 21 }
 22 // remove docs
 23 var removeDocument = function(db,removeJson,col,callback) {
 24     // Get the documents collection
 25     var collection = db.collection(col);
 26     // or use methode: remove
 27     collection.deleteOne(removeJson, function(err, result) {
 28         assert.equal(err, null);
 29         callback(result);
 30     }); 
 31 }
 32 // update docs
 33 var updateDocument = function(db,updateJson,setJson,col,callback) {
 34     // Get the documents collection
 35     var collection = db.collection(col);
 36     // Update document
 37     collection.updateMany(updateJson
 38     , { $set: setJson }, function(err, result) {
 39         assert.equal(err, null);
 40         callback(result);
 41     }); 
 42 }
 43 /*
 44 note opp
 45  */
 46 router.get('/getAllNote',function(req, res, next) {
 47     // Use connect method to connect to the server
 48     MongoClient.connect(url,function(err, db) {
 49         assert.equal(null, err);
 50         findDocuments(db,'note',function(allDocs) {
 51             db.close();
 52             res.json(allDocs);
 53         });
 54     });
 55 });
 56 
 57 router.post('/getNote',function(req, res, next) {
 58     // Use connect method to connect to the server
 59     MongoClient.connect(url,function(err, db) {
 60         assert.equal(null, err);
 61         let filterJson = {'_id':new ObjectID(req.body._id)};
 62         findDocuments(db,'note',function(allDocs) {
 63             db.close();
 64             res.json(allDocs);
 65         },filterJson);
 66     });
 67 });
 68 
 69 router.post('/addNote',function(req, res, next) {
 70     // Use connect method to connect to the server
 71     MongoClient.connect(url, function(err, db) {
 72         insertDocuments(db,req.body,'note',function(result) {
 73             db.close();
 74             res.json(result);
 75         });
 76     });
 77 });
 78 
 79 router.post('/delNote',function(req, res, next) {
 80     // Use connect method to connect to the server
 81     MongoClient.connect(url, function(err, db) {
 82         let removeJson = {'_id': new ObjectID(req.body._id)};
 83         removeDocument(db,removeJson,'note',function(result) {
 84             db.close();
 85             res.json(result);
 86         });
 87     });
 88 });
 89 
 90 router.post('/editNote',function(req, res, next) {
 91     // Use connect method to connect to the server
 92     MongoClient.connect(url, function(err, db) {
 93         let updateJson = {'_id':new ObjectID(req.body._id)};
 94         let setJson = {'time':req.body.time,'content':req.body.content,'name':req.body.name,'sts':req.body.sts};
 95         updateDocument(db, updateJson, setJson,'note',function(result) {
 96             db.close();
 97             res.json(result);
 98         });
 99     });
100 });

2.模板代碼[略,詳見附件]:

note.jade

noteDetail.html

noteList.html

noteShow.html

3.angularjs2 服務代碼:

 1 import { Injectable } from '@angular/core';
 2 import {Http,Response} from '@angular/http';
 3 import 'rxjs/add/operator/toPromise';
 4 import 'rxjs/add/operator/catch';
 5 import 'rxjs/add/operator/debounceTime';
 6 import 'rxjs/add/operator/distinctUntilChanged';
 7 import 'rxjs/add/operator/map';
 8 import 'rxjs/add/operator/switchMap';
 9 
10 @Injectable()
11 export class noteService {
12   constructor(private http: Http) {
13   }
14   getAllNote():Promise<any[]> {
15     return this.http.get('/mongodb/getAllNote').toPromise().then(res=>
16       JSON.parse(res.text()) as any[]
17     ).catch(this.handleError);
18   }
19   getNote(noteId:string):Promise<any[]> {
20     return this.http.post('/mongodb/getNote',{_id:noteId}).toPromise().then(res=>
21       JSON.parse(res.text()) as any[]
22     ).catch(this.handleError);
23   }
24   addNote(note:any):Promise<any[]> {
25     return this.http.post('/mongodb/addNote',note).toPromise().then(res=>
26       JSON.parse(res.text()) as any
27     ).catch(this.handleError);
28   }
29   delNote(note:any):Promise<any[]> {
30     return this.http.post('/mongodb/delNote',note).toPromise().then(res=>
31       JSON.parse(res.text()) as any
32     ).catch(this.handleError);
33   }
34   editNote(note:any):Promise<any[]> {
35     return this.http.post('/mongodb/editNote',note).toPromise().then(res=>
36       JSON.parse(res.text()) as any
37     ).catch(this.handleError);
38   }
39 
40   private handleError (error: Response | any) {
41     console.error(error);
42     return { };
43   }
44 }

4.angularjs2 列表顯示代碼:

import {Component, OnInit, ViewChild, Renderer, ElementRef, AfterViewInit, animate, trigger,state,style,transition} from '@angular/core';
import {Http,Response} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import { noteService } from './note.service';
import { Router,ActivatedRoute, Params }  from '@angular/router';

@Component({
  selector: 'noteList',
  templateUrl: '/noteList.html',
  styleUrls: ['stylesheets/noteList.css']
})
export class AppListComponent  implements OnInit {
    notes:any[] = [];
    constructor(private noteService: noteService,private router: Router,private route: ActivatedRoute) {
    }
    ngOnInit(){
        this.noteService.getAllNote().then(notes => this.notes=notes);
    }
  doEdit(editNote:any){
    this.router.navigate(['/noteEdit', JSON.stringify(editNote)]);
  }
  doDel(delNote:any){
    this.noteService.delNote(delNote).then(result => {
      this.noteService.getAllNote().then(notes => this.notes=notes);
    });
  }
  doShow(noteId:string){
    this.router.navigate(['/noteShow', noteId]);
  }
}

5.添加編輯顯示代碼[略,詳見附件]:

noteAddForm.component.ts [添加與修改]

noteShow.component.ts [顯示詳細]

完整源碼下載:http://download.csdn.net/detail/wangxsh42/9742804


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • FFmpeg DXVA2解碼得到的數據使用surface來承載的,surface限制很多,如果能用紋理來渲染的話,那我們就可以充分開發D3D,比如可以用坐標變換來實現電子放大的功能,還可以用坐標變換來實現視頻圖像任意角度的旋轉等功能。而對於我來說,最重要的是紋理渲染可以使得解碼後的數據能夠用像素著色... ...
  • 今天,我們來講一下建造者模式。 一、案例 我們來用winform畫一個小人,一個頭,一個身體,兩隻手,兩條腿。 我們一般想到的代碼如下: 運行的效果: 嗯,好,下麵,我們再畫一個稍微胖一點的小人。 代碼如下: 運行效果如下 咦,我們好像少花了條腿哦。 哈哈,像這樣粗心的情況我們經常出現 二、演繹 1 ...
  • 一. 許可權場景分析: 1. 系統具有角色概念, 部門概念, 且都具有相應不同的許可權 2. 用戶具有多個角色, 多個部門等關係, 並且能給單個用戶指派獨有的許可權 3. 具有細粒度許可權控制到資源的RBAC, 能控制頁面, 控制菜單, 控制邏輯, 控制單個操作, 控制到單一數據; 且具有一定的可擴展性 4 ...
  • 1.添加許可權常量 打開文件AppPermissions.cs 【..\MyCompanyName.AbpZeroTemplate.Core\Authorization\AppPermissions.cs】 在末尾添加如下常量: //分類管理許可權 public const string Pages_C ...
  • Smart Tab Overview Smart Tab is a jQuery plugin for tabbed interface. It is flexible and very easy to implement. It has a lot of features that you wil ...
  • html代碼 <div>測試文本</div>js:div.innerHTMLjQuery:div.html() ...
  • 1.定義類 2.類聲明 3.變數提升 4.類表達式 匿名的 命名的 5.原型方法 6.靜態方法 7.類繼承 8.Species 9.super 關鍵字可以用來調用其父類的構造器或者類方法 上面代碼首先用class定義了一個“類”,可以看到裡面有一個constructor方法,這就是構造方法,而thi ...
  • 最後的效果圖如下: ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...