在 Angular 部落格教學系列的上一部分中,您學習如何建立 ShowPostComponent
以在主頁上顯示部落格文章清單。您使用建立的 REST API 端點取得了從 MongoDB shell 插入的記錄。
在本教程中,您將建立一個名為 AddPostComponent
的新元件,以提供向 MongoDB 資料庫新增部落格文章的使用者介面。
開始使用
讓我們開始複製本教學系列前一部分的原始程式碼。
git clone https://github.com/royagasthyan/ShowPost AddPost
導航到專案目錄並安裝所需的依賴項。
cd AddPost/client npm install cd AddPost/server npm install
安裝依賴項後,重新啟動客戶端和伺服器應用程式。
cd AddPost/client npm start cd AddPost/server node app.js
將瀏覽器指向 http://localhost:4200,應用程式應該正在執行。
建立新增貼文元件
讓我們開始建立 AddPostComponent
。在 src/app
資料夾中建立一個名為 add-post
的資料夾。在 add-post
資料夾中,建立一個名為 add-post.component.ts
的檔案並加入以下程式碼:
import { Component } from '@angular/core'; import { Post } from '../models/post.model'; @Component({ selector: 'app-add-post', templateUrl: './add-post.component.html', styleUrls: ['./add-post.component.css'] }) export class AddPostComponent { constructor() { } }
建立一個名為 add-post.component.html
的檔案和以下 HTML 程式碼:
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 id="Modal-title">Modal title</h5> <button type="button" #closeBtn class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <form> <div class="form-group"> <label for="exampleInputEmail1">Title</label> <input name="title" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter title"> </div> <div class="form-group"> <label for="exampleInputPassword1">Description</label> <textarea name="description" class="form-control" id="exampleInputPassword1" placeholder="Password"> </textarea> </div> <button type="button" class="btn btn-primary">Add</button> </form> </div> </div> </div> </div>
您將以彈出視窗的形式顯示新增貼文元件。
現在您需要將 AddPostComponent
新增到 NgModule
。在 app.module.ts
檔案中導入 AddPostComponent
。
import { AddPostComponent } from './add-post/add-post.component';
將該元件新增至 NgModule
declarations
清單。其外觀如下:
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { ROUTING } from './app.routing'; import { FormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { RootComponent } from './root/root.component'; import { LoginComponent } from './login/login.component'; import { HomeComponent } from './home/home.component'; import { ShowPostComponent } from './show-post/show-post.component'; import { AddPostComponent } from './add-post/add-post.component'; @NgModule({ declarations: [ RootComponent, LoginComponent, HomeComponent, ShowPostComponent, AddPostComponent ], imports: [ BrowserModule, ROUTING, FormsModule, HttpClientModule ], providers: [], bootstrap: [RootComponent] }) export class AppModule { }
要觸發新增貼文彈出窗口,您已經將 data-target
屬性新增到 home.component.html
中的按鈕。
<button type="button" class="btn btn-link" data-toggle="modal" data-target="#exampleModal"> Add </button>
儲存上述變更並重新啟動應用程式。登入應用程式並點擊主頁中的新增連結。您將看到 AddPostComponent
顯示為彈出視窗。
實作新增貼文功能
將 ngModel
指令加入到 title
和 description
的輸入元素。
<input name="title" type="text" [(ngModel)]="post.title" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter title"> <textarea name="description" [(ngModel)]="post.description" class="form-control" id="exampleInputPassword1" placeholder="Password"> </textarea>
在按鈕中新增 click
指令,用來呼叫儲存博文的方法。
<button (click)="addPost()" type="button" class="btn btn-primary">Add</button>
從 add-post.component.ts
檔案中的 src/app/models/post.model.ts
匯入 Post
模型.
import { Post } from '../models/post.model';
在 add-post.component.ts
檔案中定義 post
變數。
public post : Post;
在 add-post.component.ts
檔案中定義 addPost
方法。在 addPost
方法中,您將驗證輸入的 title
和 description
並呼叫服務方法以呼叫 REST API。方法如下所示:
addPost() { if(this.post.title && this.post.description){ // call the service method to add post } else { alert('Title and Description required'); } }
讓我們為元件 AddPostComponent
建立服務文件。建立一個名為 add-post.service.ts
的檔案並新增以下程式碼:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Post } from '../models/post.model'; @Injectable() export class AddPostService { constructor(private http: HttpClient){ } }
在 AddPostService
內,建立一個名為 addPost
的方法來進行 REST API 呼叫。
addPost(post: Post){ return this.http.post('/api/post/createPost',{ title : post.title, description : post.description }) }
如上面的程式碼所示,您使用了 HttpClient
來進行 API 呼叫並傳回 Observable
。
在add-post.component.ts
檔案內的addPost
方法中,您將從addPost
方法class="inline"> add-post.service.ts 檔案。
this.addPostService.addPost(this.post).subscribe(res =>{ // response from REST API call });
以下是 add-post.component.ts
檔案的外觀:
import { Component } from '@angular/core'; import { AddPostService } from './add-post.service'; import { Post } from '../models/post.model'; @Component({ selector: 'app-add-post', templateUrl: './add-post.component.html', styleUrls: ['./add-post.component.css'], providers: [ AddPostService ] }) export class AddPostComponent { public post : Post; constructor(private addPostService: AddPostService) { this.post = new Post(); } addPost() { if(this.post.title && this.post.description){ this.addPostService.addPost(this.post).subscribe(res =>{ console.log('response is ', res) }); } else { alert('Title and Description required'); } } }
建立用於新增貼文的 REST API
讓我們建立一個 REST API 端點,用於將部落格文章新增到 MongoDB 資料庫。在 server/app.js
檔案中,建立一個 API 端點,如下所示:
app.post('/api/post/createPost', (req, res) => { // insert the details to MongoDB })
首先,您需要使用 Mongoose
用戶端連接到 MongoDB 資料庫。
mongoose.connect(url, { useMongoClient: true }, function(err){ if(err) throw err; console.log('connection established '); });
建立連線後,您需要使用 Post
架構(在 server/model/post.js
檔案中定義)建立模型物件。
const post = new Post({ title: req.body.title, description: req.body.description })
如上面的程式碼所示,您使用從請求 req
物件傳入的 title
和 description
建立了 Post 物件。
在 Post 物件上呼叫 save
方法將項目儲存到 MongoDB。
post.save((err, doc) => { if(err) throw err; return res.status(200).json({ status: 'success', data: doc }) })
如上面的代码所示,一旦调用 save
方法回调且没有错误,它将返回 success
消息以及返回的对象 doc
。
以下是 REST API 端点的最终外观:
app.post('/api/post/createPost', (req, res) => { mongoose.connect(url, { useMongoClient: true }, function(err){ if(err) throw err; const post = new Post({ title: req.body.title, description: req.body.description }) post.save((err, doc) => { if(err) throw err; return res.status(200).json({ status: 'success', data: doc }) }) }); })
保存上述更改并重新启动 Angular 和 Node 服务器。登录应用程序并尝试添加新的博客文章。单击添加按钮后,检查浏览器控制台,您将记录成功响应。
当博客文章详细信息成功添加到数据库后,您需要关闭弹出窗口。为了关闭弹出窗口,您需要以编程方式单击一个关闭按钮。
您将使用 @ViewChild
装饰器来访问关闭按钮。
在 AddPostComponent
中导入 ViewChild
和 ElementRef
。
import { Component, ViewChild, ElementRef } from '@angular/core';
在 AddPostComponent
内,定义以下变量:
@ViewChild('closeBtn') closeBtn: ElementRef;
使用以下代码启动 closeBtn
单击:
this.closeBtn.nativeElement.click();
将上述代码添加到addPost
方法的成功回调中。这是 addPost
方法,来自 add-post.component.ts
。
addPost() { if(this.post.title && this.post.description){ this.addPostService.addPost(this.post).subscribe(res =>{ this.closeBtn.nativeElement.click(); }); } else { alert('Title and Description required'); } }
保存更改并重新启动客户端服务器。登录应用程序并尝试添加新的博客文章。成功保存博客文章详细信息后,弹出窗口将关闭。
刷新博客列表
需要注意的一件事是,新添加的博客文章不会显示在博客文章列表中。所以需要添加一个触发器来通知何时更新ShowPostComponent
。您将使用通用服务在两个组件之间进行通信。
在 src/app
文件夹中创建一个名为 service
的文件夹。使用以下代码创建一个名为 common.service.ts
的文件:
import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; @Injectable() export class CommonService { public postAdded_Observable = new Subject(); constructor(){ } notifyPostAddition(){ this.postAdded_Observable.next(); } }
如上面的代码所示,您已声明一个名为 postAdded_Observable
的 Subject
来跟踪添加到数据库中的新博客文章。每当新的博客文章添加到数据库时,您将调用 notifyPostAddition
方法,该方法将通知订阅者有关更新的信息。
在 app.module.ts
中导入 CommonService
并将其包含在 NgModule
提供商列表中。其外观如下:
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { ROUTING } from './app.routing'; import { FormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { RootComponent } from './root/root.component'; import { LoginComponent } from './login/login.component'; import { HomeComponent } from './home/home.component'; import { ShowPostComponent } from './show-post/show-post.component'; import { AddPostComponent } from './add-post/add-post.component'; import { CommonService } from './service/common.service'; @NgModule({ declarations: [ RootComponent, LoginComponent, HomeComponent, ShowPostComponent, AddPostComponent ], imports: [ BrowserModule, ROUTING, FormsModule, HttpClientModule ], providers: [CommonService], bootstrap: [RootComponent] }) export class AppModule { }
在 show-post.component.ts
文件中导入 CommonService
并在构造方法中初始化。
import { CommonService } from '../service/common.service';
constructor(private showPostService: ShowPostService, private commonService: CommonService) { }
在 ngOnInit
方法内,订阅 postAdded_Observable
变量并加载 getAllPost
方法。以下是 ngOnInit
方法的外观:
ngOnInit(){ this.getAllPost(); this.commonService.postAdded_Observable.subscribe(res => { this.getAllPost(); }); }
在 add-post.component.ts
文件中导入 CommonService
,并在添加博客文章后调用 notifyPostAddition
方法。以下是 AddPostComponent
中的 addPost
方法的外观:
addPost() { if(this.post.title && this.post.description){ this.addPostService.addPost(this.post).subscribe(res =>{ this.closeBtn.nativeElement.click(); this.commonService.notifyPostAddition(); }); } else { alert('Title and Description required'); } }
保存以上更改并重新启动客户端服务器。登录到应用程序并添加新的博客文章。添加后,博客文章列表将更新为新的博客文章。
总结
在本教程中,您创建了 AddPostComponent
以将博客文章详细信息添加到 MongoDB 数据库。您使用 Mongoose
客户端创建了 REST API,用于将博客文章保存到 MongoDB 数据库。
在本系列的下一部分中,您将实现编辑和更新博客文章详细信息的功能。
本教程的源代码可在 GitHub 上获取。
到目前为止您的体验如何?请在下面的评论中告诉我您的宝贵建议。
以上是Angular 和 MongoDB:向部落格應用程式添加帖子的詳細內容。更多資訊請關注PHP中文網其他相關文章!

JavaScript在Web開發中的主要用途包括客戶端交互、表單驗證和異步通信。 1)通過DOM操作實現動態內容更新和用戶交互;2)在用戶提交數據前進行客戶端驗證,提高用戶體驗;3)通過AJAX技術實現與服務器的無刷新通信。

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

Python和JavaScript在社區、庫和資源方面的對比各有優劣。 1)Python社區友好,適合初學者,但前端開發資源不如JavaScript豐富。 2)Python在數據科學和機器學習庫方面強大,JavaScript則在前端開發庫和框架上更勝一籌。 3)兩者的學習資源都豐富,但Python適合從官方文檔開始,JavaScript則以MDNWebDocs為佳。選擇應基於項目需求和個人興趣。

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

JavaScript在現實世界中的應用包括服務器端編程、移動應用開發和物聯網控制:1.通過Node.js實現服務器端編程,適用於高並發請求處理。 2.通過ReactNative進行移動應用開發,支持跨平台部署。 3.通過Johnny-Five庫用於物聯網設備控制,適用於硬件交互。

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

Dreamweaver Mac版
視覺化網頁開發工具

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。