In the previous part of this tutorial series you learnt how to create the add post component to add new blog posts. You learnt how to create the REST API endpoint to add a new post to the MongoDB database.
In this part of the tutorial series, you’ll learn how to implement the functionality to edit an existing blog post from the blog post list.
Getting Started
Let’s get started by cloning the source code from the last part of the tutorial series.
git clone https://github.com/royagasthyan/AngularBlogApp-Post EditPost
Navigate to the project directory and install the required dependencies.
cd EditPost/client npm install cd EditPost/server npm install
Once you have the dependencies installed, restart the client and server application.
cd EditPost/client npm start cd EditPost/server node app.js
Point your browser to http://localhost:4200 and you will have the application running.
Adding the Edit Post View
In the ShowPostComponent
, you’ll add two icons for editing and deleting the blog post. You’ll make use of Font Awesome to display the edit and delete icons.
Download and include the font awesome folder in the assets
folder.
In the src/app/index.html
page, include a reference to the font awesome CSS
style.
Now modify the show-post/show-post.component.html
file to include the HTML for the edit and delete icons.
Here is how the show-post.component.html
file looks:
{{post.title}}
3 days ago{{post.description}}
read more...
Save the above changes and restart the client application. Log into the application and you will be able to view the edit and delete icons corresponding to each listed blog post.
Populating the Edit Detail in a Popup
When the user clicks the edit icon corresponding to any blog post, you need to populate the blog post details in the add post popup for updating.
Add a click method to the edit icon.
Inside the CommonService
, you need to define an observable to keep track of when the edit button is clicked. Define the observable as shown:
public postEdit_Observable = new Subject();
Define another variable to keep track of the post to be edited.
public post_to_be_edited; constructor(){ this.post_to_be_edited = new Post(); }
Whenever the edit button is clicked, you’ll keep the post to be edited in the CommonService
and trigger the observable to notify of post edit. Define two methods to set the post to be edited and to notify post edit.
notifyPostEdit(){ this.postEdit_Observable.next(); } setPostToEdit(post: Post){ this.post_to_be_edited = post; this.notifyPostEdit(); }
Inside the click method, you’ll call the setPostToEdit
method from CommonService
. Here is how the editPost
method looks:
editPost(post: Post){ this.commonService.setPostToEdit(post); }
You will have the post detail in the common service when the user clicks the edit button. To show the add post popup for updating, you need to click the add post button programmatically.
Inside the home/home.component.html
file, add a #
identifier to the add post button.
Import ViewChild
and ElementRef
inside the home.component.ts
file.
import { Component, ViewChild, ElementRef } from '@angular/core';
Define a reference to the add button inside the home.component.ts
file.
@ViewChild('addPost') addBtn: ElementRef;
Inside the HomeComponent
constructor, subscribe to the postEdit_Observable
from CommonService
. On calling the postEdit_Observable
subscription callback, invoke the add button click to show the popup. Here is how the home.component.ts
file looks:
import { Component, ViewChild, ElementRef } from '@angular/core'; import { CommonService } from '../service/common.service'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent { @ViewChild('addPost') addBtn: ElementRef; constructor(private commonService: CommonService){ this.commonService.postEdit_Observable.subscribe(res => { this.addBtn.nativeElement.click(); }); } }
You need to subscribe to postEdit_Observable
in the add-post.component.ts
file to set the post to be edited on the post
variable. Here is how the ngOnInit
method in add-post.component.ts
looks:
ngOnInit(){ this.commonService.postEdit_Observable.subscribe(res => { this.post = this.commonService.post_to_be_edited; }); }
Save the above changes and restart the client server. Log into the application and click on the edit button against any blog post. You will be able to view the post details populated in the add post popup.
Creating the Update Post REST API
Inside server/app.js
, let’s define another REST API endpoint to update post details based on the ID of the post. Here is how it looks:
app.post('/api/post/updatePost', (req, res) => { })
Let’s first use Mongoose
to connect to the MongoDB database.
app.post('/api/post/updatePost', (req, res) => { mongoose.connect(url, { useMongoClient: true }, function(err){ console.log('connection established'); }); })
Once the connection is established, you make use of the update
method on the Post model.
Post.update( {_id: req.body.id }, { title : req.body.title, description: req.body.description }, (err, doc) => { if(err) throw err; })
You’ll be updating the post based on the ID
of the post passed. As seen in the above code, you have specified the post _id
to be updated. In the second option, you have specified the fields to be updated, which are title
and description
.
Once the details get updated, you’ll return the status
along with the number of rows affected during the update. Here is how the REST API endpoint for the post update looks:
app.post('/api/post/updatePost', (req, res) => { mongoose.connect(url, { useMongoClient: true }, function(err){ if(err) throw err; Post.update( {_id: req.body.id }, { title : req.body.title, description: req.body.description }, (err, doc) => { if(err) throw err; return res.status(200).json({ status: 'success', data: doc }) }) }); })
Making the REST API Call to Update
The ID
returned for each post from the MongoDB is _id
, so you need to modify the id
of our model src/app/models/post.model.ts
. Here is how it looks:
export class Post { constructor(){ this._id = ''; this.title = ''; this.description = ''; } public _id; public title; public description; }
When you click the add post button, the method called will be addPost
. Inside the addPost
method in add-post.component.ts
, you’ll check if the post
object has an _id
. If an _id
is present then you need to call the update method from the service, else you’ll call the add post service method.
Create a method called updatePost
inside the add-post.service.ts
file.
updatePost(post: Post){ return this.http.post('/api/post/updatePost',{ id: post._id, title : post.title, description : post.description }) }
Here is how the modified addPost
method from the add-post.component.ts
file looks:
addPost() { if(this.post.title && this.post.description){ if(this.post._id){ this.addPostService.updatePost(this.post).subscribe(res =>{ this.closeBtn.nativeElement.click(); this.commonService.notifyPostAddition(); }); } else { this.addPostService.addPost(this.post).subscribe(res =>{ this.closeBtn.nativeElement.click(); this.commonService.notifyPostAddition(); }); } } else { alert('Title and Description required'); } }
Save the above changes and restart both Angular and Node server. Log into the application and try editing a post. You will have a popup displayed to edit the details on clicking the edit button. Click the add button and the details will be updated and displayed in the blog post list.
Wrapping It Up
In this tutorial, you implemented the functionality to update the existing blog post details. You created the back-end REST API endpoint to update the blog post details based on the blog post ID. You made use of the Mongoose
client to update the details of the blog post in the MongoDB database.
In the next part, you’ll implement the delete post and log out functionality.
How was your experience so far? Do let us know your thoughts, suggestions, or any corrections in the comments below.
Source code from this tutorial is available on GitHub.
Powered by WPeMatico