在这一部分中,您将实现删除现有博客文章和实现用户注销功能的功能。
入门
让我们从克隆教程系列最后一部分的源代码开始。
git clone https://github.com/royagasthyan/angularBlogApp-EditUpdate Deletepost
导航到项目目录并安装所需的依赖项。
cd DeletePost/client npm install cd DeletePost/server npm install
cd DeletePost/client npm start cd DeletePost/servernode app.js
将您的浏览器指向 http://localhost:4200 ,您将运行该应用程序。
添加 删除确认
您已将删除图标添加到列出的博客文章中。当用户单击任何博客文章对应的删除图标时,您需要显示删除确认弹出窗口。如果用户确认删除过程,则只需要删除博客文章。
让我们开始在用户单击删除按钮时添加模式弹出确认。将以下模式弹出代码添加到show-post.component.html
文件中。
<div class="modal fade" id="deleteModal" 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">Delete Post</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> Are you sure ? </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button> <button type="button" class="btn btn-primary">Delete</button> </div> </div> </div> </div>
修改删除图标以包含data-target
属性,如下所示:
<i data-toggle="modal" data-target="#deleteModal" title="Delete" class="fas fa-trash-alt" aria-hidden="true"></i>
保存上述更改并重新启动客户端服务器。登录应用程序并单击任何博客文章对应的删除图标,您将弹出确认模式。
创建删除博客文章api
让我们创建一个 rest API 端点来删除博客文章。在 server/app.js
文件中,创建一个 REST API 端点来处理基于 blog post 的 blog post 删除id
。以下是 REST API 端点的外观:
app.post('/api/post/deletePost', (req, res) => { })
mongoose.connect(url, { useMongoClient: true }, function(err){ // connection established });
您将使用该 findByIdAndRemove
方法使用 查找博客文章并将其 id
删除。成功删除博客文章后,您将返回status
回复。以下是 REST API 端点的外观:
app.post('/api/post/deletePost', (req, res) => { mongoose.connect(url, { useMongoClient: true }, function(err){ if(err) throw err; Post.findByIdAndRemove(req.body.id, (err, doc) => { if(err) throw err; return res.status(200).json({ status: 'success', data: doc }) }) }); })
调用 Delete API
当用户单击删除图标时,您需要将帖子详细信息保存在变量中。如果用户在确认后继续执行删除选项,您将调用删除 REST API。
setDelete
添加一个在删除按钮单击时调用的方法 show-post.component.html
。这是它的外观:
<i (click)="setDelete(post)" data-toggle="modal" data-target="#deleteModal" title="Delete" class="fas fa-trash-alt" aria-hidden="true"> </i>
在show-post.component.ts
文件中,定义一个名为 post_to_delete
.
setDelete
定义内部调用的方法show-post.component.ts
以保留要删除的帖子详细信息。
setDelete(post: Post){ this.post_to_delete = post; }
当用户点击弹出框的取消按钮时,需要调用一个被调用的方法将 unsetDelete
其设置post_to_delete
为null。这是它的外观:
unsetDelete(){ this.post_to_delete = null; }
以下是Cancel
按钮 HTML 代码的show-post.component.html
外观:
<button #closeBtn (click)="unsetDelete()" type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
现在让我们定义文件中调用的服务deletePost
方法show-post.service.ts
。这是它的外观:
deletePost(id){ return this.http.post('/api/post/deletePost',{id : id}) }
要从 调用服务方法ShowPostComponent
,请定义一个调用的方法,该方法deletePost
将从 订阅该deletePost
方法ShowPostService
。这是看起来的deletePost
方法:ShowPostComponent
deletePost(){ this.showPostService.deletePost(this.post_to_delete._id).subscribe(res => { this.getAllPost(); }) }
一旦帖子被删除,您需要刷新帖子列表,因此您需要调用该getAllPost
方法。删除成功后,您还需要关闭弹出窗口。
首先,在 文件中导入对ViewChild
和的引用。ElementRef
show-post.component.ts
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
定义一个变量 closeBtn
来创建对弹出关闭按钮的引用。
@ViewChild('closeBtn') closeBtn: ElementRef;
现在,当删除调用成功时,您需要关闭删除确认弹出窗口。
修改后的deletePost
方法如下所示:
deletePost(){ this.showPostService.deletePost(this.post_to_delete._id).subscribe(res => { this.getAllPost(); this.closeBtn.nativeElement.click(); }) }
这是show-post.component.ts
文件的外观:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core'; import { ShowPostService } from './show-post.service'; import { Post } from '../models/post.model'; import { CommonService, } from '../service/common.service'; @Component({ selector: 'app-show-post', templateUrl: './show-post.component.html', styleUrls: ['./show-post.component.css'], providers: [ ShowPostService ] }) export class ShowPostComponent implements OnInit { @ViewChild('closeBtn') closeBtn: ElementRef; public posts : any []; public post_to_delete; constructor(private showPostService: ShowPostService, private commonService: CommonService) { } ngOnInit(){ this.getAllPost(); this.commonService.postAdded_Observable.subscribe(res => { this.getAllPost(); }); } setDelete(post: Post){ this.post_to_delete = post; } unsetDelete(){ this.post_to_delete = null; } getAllPost(){ this.showPostService.getAllPost().subscribe(result => { console.log('result is ', result); this.posts = result['data']; }); } editPost(post: Post){ this.commonService.setPostToEdit(post); } deletePost(){ this.showPostService.deletePost(this.post_to_delete._id).subscribe(res => { this.getAllPost(); this.closeBtn.nativeElement.click(); }) } }
保存上述更改并重新启动客户端和服务器应用程序。登录应用程序并单击与任何博客文章对应的删除图标。您将弹出一个确认框。确认博文删除,博文将被删除并更新博文列表。
在登录期间处理用户会话
当用户登录应用程序时,您将登录的用户名保存在localstorage
. 修改validateLogin
里面的方法LoginComponent
,将登录的用户名存储在localstorage
.
验证 API 调用的结果后,添加以下代码以存储登录的用户名。
localStorage.setItem('loggedInUser', this.user.username);
以下是该validateLogin
方法的外观:
validateLogin() { if(this.user.username && this.user.password) { this.loginService.validateLogin(this.user).subscribe(result => { if(result['status'] === 'success') { localStorage.setItem('loggedInUser', this.user.username); this.router.navigate(['/home']); } else { alert('Wrong username password'); } }, error => { console.log('error is ', error); }); } else { alert('enter user name and password'); } }
现在,在home.component.html
文件中,添加一个调用logout
注销按钮的方法。
<button (click)="logout()" type="button" class="btn btn-link"> Logout </button>
在home.component.ts
文件中,创建一个名为logout
. 在logout
方法内部,您需要清除loggedInUser
. 以下是该方法的外观:
logout(){ localStorage.removeItem('loggedInUser'); this.router.navigate(['/']); }
在HomeComponent
的构造方法中,需要添加对loggedInUser
本地存储键的检查。如果没有找到,您需要重定向到登录页面。这是home.component.ts
文件的外观:
import { Component, ViewChild, ElementRef } from '@angular/core'; import { CommonService } from '../service/common.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent { @ViewChild('addPost') addBtn: ElementRef; constructor(private commonService: CommonService, private router: Router){ if(!localStorage.getItem('loggedInUser')){ this.router.navigate(['/']); } this.commonService.postEdit_Observable.subscribe(res => { this.addBtn.nativeElement.click(); }); } logout(){ localStorage.removeItem('loggedInUser'); this.router.navigate(['/']); } }
保存上述更改并重新启动客户端服务器。尝试通过 在浏览器窗口中加载 URL http://localhost:4200/home来访问主页。您将被重定向到登录页面。
登录应用程序并单击注销按钮。您将被注销并重定向到登录页面。
概括
在本教程系列的这一部分中,您学习了如何通过在博客文章列表中添加图标来实现博客文章删除。您还创建了一个 REST API,用于使用客户端从 MongoDB 数据库中删除博客文章详细信息Mongoose
。
您只实现了博客应用程序的基本功能,并且可以进一步开发此应用程序以包含更多功能。
您学习使用 Angular 和 MongoDB 创建博客应用程序的经验如何?请在下面的评论中告诉我们您的想法和建议。
本教程的源代码可在GitHub 上获得。