在 angular 博客教程系列的前一部分中,您学习了如何创建在
ShowpostComponent
主页上显示博客文章列表的方法。您fetch使用创建的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/servernode app.js
将浏览器指向 http://localhost:4200 ,您应该可以运行应用程序。
创建添加帖子组件
让我们从创建AddPostComponent
. add-post
在文件夹内 创建一个名为的src/app
文件夹。在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 class="modal-title" id="exampleModalLabel">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
. AddPostComponent
在app.module.ts
文件中导入。
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
显示为弹出窗口。
实现 Add Post 功能
将指令添加到和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>
从文件中 导入Post
模型。src/app/models/post.model.ts
add-post.component.ts
import { Post } from '../models/post.model';
在文件中定义post
变量。add-post.component.ts
public post : Post;
在文件中定义addPost
方法。add-post.component.ts
通过该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
方法 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 })
首先,您需要使用客户端连接到 MongoDB 数据库mongoose
。
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 })
如上面的代码所示,您使用请求对象创建了 Post 对象title
并传入。description
req
调用save
Post 对象上的方法将条目保存到 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
装饰器来访问关闭按钮。
导入ViewChild
并ElementRef
在AddPostComponent
.
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
. 您将使用公共服务在两个组件之间进行通信。
service
在文件夹内创建一个名为的src/app
文件夹。创建一个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(); } }
如上面的代码所示,您已经声明了一个Subject
调用postAdded_Observable
来跟踪添加到数据库的新博客文章。每当将新的博客文章添加到数据库时,您将调用该notifyPostAddition
方法,该方法将通知订阅者有关更新的信息。
导入CommonService
inapp.module.ts
并将其包含在 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 { }
CommonService
在 文件中导入show-post.component.ts
并在构造函数方法中对其进行初始化。
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(); }); }
添加博客文章后CommonService
,导入 add-post.component.ts
文件并调用该 方法。notifyPostAddition
这是看起来的addPost
方法:AddPostComponent
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 数据库的方法。您创建了 REST API 以使用客户端将博客文章保存到 MongoDB 数据库 Mongoose
。
在本系列的下一部分中,您将实现编辑和更新博客文章详细信息的功能。
本教程的源代码可在 GitHub 上获得。