• 日常搜索
  • 百度一下
  • Google
  • 在线工具
  • 搜转载

使用Angular和MongoDB创建博客应用程序:添加帖子

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  ,您应该可以运行应用程序。

创建添加帖子组件

让我们从创建AddPostComponentadd-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">&times;</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>

您将在弹出窗口中显示添加帖子组件。

现在您需要AddPostComponentNgModuleAddPostComponent 在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显示为弹出窗口。

使用Angular和MongoDB创建博客应用程序:添加帖子  第1张

实现 Add Post 功能

将指令添加到ngModel的输入元素titledescription

<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.tsadd-post.component.ts

import { Post } from '../models/post.model';

在文件中定义post变量。add-post.component.ts

public post : Post;

在文件中定义addPost方法。add-post.component.ts通过该addPost方法,您将验证输入的内容titledescription并调用服务方法以调用 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并传入descriptionreq

调用savePost 对象上的方法将条目保存到 MongoDB。

post.save((err, doc) => {
	if(err) throw err;
	return res.status(200).json({
		status: 'success',
		data: doc
	})
})

从上面的代码中可以看出,一旦回调save方法没有错误被调用,它会连同返回的对象一起返回消息successdoc

以下是 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装饰器来访问关闭按钮。

导入ViewChildElementRefAddPostComponent.

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方法,该方法将通知订阅者有关更新的信息。

导入CommonServiceinapp.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 上获得。


文章目录
  • 入门
  • 创建添加帖子组件
  • 实现 Add Post 功能
  • 为添加帖子创建 REST API
  • 刷新博客列表
  • 概括