In the last part of the tutorial series, you saw how to write the REST API endpoint for user login. You used Mongoose to interact with MongoDB from Node. After successful validation, you saw how to use Angular Router
for navigating to the HomeComponent
.
In this part of the tutorial series, you’ll create a component to list the blog post details on the home page.
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-Home AngularBlogApp-Post
Navigate to the project directory and install the required dependencies.
cd AngularBlogApp-Post/client npm install cd AngularBlogApp-Post/server npm install
Once you have the dependencies installed, restart the client and server application.
cd AngularBlogApp-Post/client npm start cd AngularBlogApp-Post/server node app.js
Point your browser to http://localhost:4200 and you should have the application running.
Creating the Show Post Component
Once the user gets logged into the application, you’ll display the HomeComponent
. HomeComponent
acts like a wrapper component for all the components displayed inside it. You’ll be displaying the list of blog posts added by the user in the HomeComponent
.
To display the blog posts, let’s create a new component called ShowPostComponent
. Create a folder called show-post
inside the src/app
folder. Inside the show-post
folder, create a file called show-post.component.html
and add the following HTML code:
List group item heading
3 days agoDonec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.
Donec id elit non mi porta.List group item heading
3 days agoDonec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.
Donec id elit non mi porta.List group item heading
3 days agoDonec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.
Donec id elit non mi porta.
Create a file called show-post.component.ts
which will contain the ShowPostComponent
class. Here is how it looks:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-show-post', templateUrl: './show-post.component.html' }) export class ShowPostComponent implements OnInit { constructor() { } ngOnInit(){ } }
Import the ShowPostComponent
in the app.module.ts
file.
import { ShowPostComponent } from './show-post/show-post.component';
Add ShowPostComponent
in the NgModule
in the app.module.ts
file.
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'; @NgModule({ declarations: [ RootComponent, LoginComponent, HomeComponent, ShowPostComponent ], imports: [ BrowserModule, ROUTING, FormsModule, HttpClientModule ], providers: [], bootstrap: [RootComponent] }) export class AppModule { }
Modify the home.component.html
file to include the ShowPostComponent
selector.
Here is how the modified home.component.html
file looks:
Angular Blog App
Save the above changes and refresh the client application. On signing into the application, you will be able to view the blog posts listed.
Creating the Show Post Component Service
The data displayed in the ShowPostComponent
service displays hard-coded data. You’ll need a service to query the blog post list from the MongoDB database. Let’s create a service for your ShowPostComponent
.
Create a file called show-post.service.ts
in src/app/show-post
and add the following code:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable() export class ShowPostService { constructor(private http: HttpClient){ } }
Inside the ShowPostService
, create a method called getAllPost
, which will make the REST API call to get the blog post list. Here is how it looks:
getAllPost(){ return this.http.post('/api/post/getAllPost',{}) }
Here is how the show-post.service.ts
file looks:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Post } from '../models/post.model'; @Injectable() export class ShowPostService { constructor(private http: HttpClient){ } getAllPost(){ return this.http.post('/api/post/getAllPost',{}) } }
Next, you need to write down the REST API to query the MongoDB collection to get the list of blog posts.
On the server side, let’s get started by creating the model for the post. Inside the models
folder, create a file called post.js
. Require the Mongoose
module and create a schema for the blog post and export it. Here is how the /server/models/post.js
looks:
const mongoose = require('mongoose'); const Schema = mongoose.Schema; // create a schema const postSchema = new Schema({ title: { type: String, required: true }, description: { type: String, required: true } }, { collection : 'post' }); const Post = mongoose.model('Post', postSchema); module.exports = Post;
Export the above defined post.js
file in app.js
.
const Post = require('./model/post');
Create an API endpoint /api/post/getAllPost
for fetching the list of blog posts. Use the mongoose
client to connect to the MongoDB database.
app.post('/api/post/getAllPost', (req, res) => { mongoose.connect(url, { useMongoClient: true } , function(err){ if(err) throw err; console.log('connection established successfully'); }); })
Once you have the connection established, you can use the Post
model to find the list of blog posts.
Post.find({},[],{},(err, doc) => { if(err) throw err; console.log('result is ',doc); })
The .find
callback returns the list of documents.
The documents returned will be in ascending order, so add a condition to sort the blog posts in descending order.
Post.find({},[],{ sort: { _id: -1 } },(err, doc) => { if(err) throw err; })
Once you have the list of documents queried from the database, return the data along with the status
. Here is how the REST API looks:
app.post('/api/post/getAllPost', (req, res) => { mongoose.connect(url, { useMongoClient: true } , function(err){ if(err) throw err; Post.find({},[],{ sort: { _id: -1 } },(err, doc) => { if(err) throw err; return res.status(200).json({ status: 'success', data: doc }) }) }); })
Making the API Call
In the show-post.component.ts
file, define an array list for keeping the results of the API call.
public posts : any [];
Import the ShowPostService
in the ShowPostComponent
.
import { ShowPostService } from './show-post.service';
Add the ShowPostService
as a provider to the ShowPostComponent
.
@Component({ selector: 'app-show-post', templateUrl: './show-post.component.html', styleUrls: ['./show-post.component.css'], providers: [ ShowPostService ] })
Define a method called getAllPost
to make a call to the service method. Here is how it looks:
getAllPost(){ this.showPostService.getAllPost().subscribe(result => { this.posts = result['data']; }); }
As seen in the above code, the result data is set to the posts
variable.
Make a call to the above defined method from the ngOnInit
method, so that the blog post details are fetched as soon as the component is initialized.
ngOnInit(){ this.getAllPost(); }
Here is how the show-post.component.ts
file looks:
import { Component, OnInit } from '@angular/core'; import { ShowPostService } from './show-post.service'; @Component({ selector: 'app-show-post', templateUrl: './show-post.component.html', styleUrls: ['./show-post.component.css'], providers: [ ShowPostService ] }) export class ShowPostComponent implements OnInit { public posts : any []; constructor(private showPostService: ShowPostService) { } ngOnInit(){ this.getAllPost(); } getAllPost(){ this.showPostService.getAllPost().subscribe(result => { this.posts = result['data']; }); } }
Rendering the Blog Posts
The MongoDB collection might not have entries to be queried. So let’s add a few entries in the MongoDB from the mongo
shell.
Enter the MongoDB shell by typing in the following command:
mongo
Once you enter the mongo
shell, check the database available in the MongoDB database.
show collections;
Select the blogDb
database from the listed entries.
use blogDb
Create a collection named post
.
db.createCollection('post')
Insert a couple of entries into the post
collection.
db.post.insert( { title : 'TutsPlus Python Entry', description : 'Welcome to official entry of TutsPlus Python programming session' } )
Now let’s bind our posts
variable in the ShowPostComponent
to the HTML code.
You’ll be making use of the ngFor
directive to iterate over the posts
variable and display the blog posts. Modify the show-post.component.html
file as shown:
{{post.title}}
3 days ago{{post.description}}
read more...
Save the above changes and restart the client and REST API server. Sign in to the application and you will have the inserted records from MongoDB displayed on the home page.
Wrapping It Up
In this tutorial, you created the ShowPostComponent
to display the blog post details from the MongoDB
database. You created the REST API for querying the MongoDB database using the Mongoose
client from the Node server.
In the next part of the tutorial series, you’ll learn how to create the AddPostComponent
for adding new posts from the application user interface.
Source code for this tutorial is available on GitHub.
How was your experience so far? Do let me know your valuable suggestions in the comments below.
Powered by WPeMatico