Advertisement
  1. Code
  2. JavaScript
  3. Angular

Creating a Blogging App Using Angular & MongoDB: Show Post

Scroll to top
This post is part of a series called Creating a Blogging App Using Angular & MongoDB.
Creating a Blogging App Using Angular & MongoDB: Home
Creating a Blogging App Using Angular & MongoDB: Add Post

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.

1
git clone https://github.com/royagasthyan/AngularBlogApp-Home AngularBlogApp-Post

Navigate to the project directory and install the required dependencies.

1
cd AngularBlogApp-Post/client
2
npm install

3
cd  AngularBlogApp-Post/server
4
npm install

Once you have the dependencies installed, restart the client and server application.

1
cd AngularBlogApp-Post/client
2
npm start
3
cd  AngularBlogApp-Post/server
4
node app.js

Point your browser to http://localhost:4200 and you should have the application running.

Angular Blogging AppAngular Blogging AppAngular Blogging App

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:

1
<div class="list-group">
2
  <a href="#" class="list-group-item list-group-item-action flex-column align-items-start active">
3
    <div class="d-flex w-100 justify-content-between">
4
      <h5 class="mb-1">List group item heading</h5>
5
      <small>3 days ago</small>
6
    </div>
7
    <p class="mb-1">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p>
8
    <small>Donec id elit non mi porta.</small>
9
  </a>
10
  <a href="#" class="list-group-item list-group-item-action flex-column align-items-start">
11
    <div class="d-flex w-100 justify-content-between">
12
      <h5 class="mb-1">List group item heading</h5>
13
      <small class="text-muted">3 days ago</small>
14
    </div>
15
    <p class="mb-1">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p>
16
    <small class="text-muted">Donec id elit non mi porta.</small>
17
  </a>
18
  <a href="#" class="list-group-item list-group-item-action flex-column align-items-start">
19
    <div class="d-flex w-100 justify-content-between">
20
      <h5 class="mb-1">List group item heading</h5>
21
      <small class="text-muted">3 days ago</small>
22
    </div>
23
    <p class="mb-1">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p>
24
    <small class="text-muted">Donec id elit non mi porta.</small>
25
  </a>
26
</div>

Create a file called show-post.component.ts which will contain the ShowPostComponent class. Here is how it looks:

1
import { Component, OnInit } from '@angular/core';
2
3
@Component({
4
  selector: 'app-show-post',
5
  templateUrl: './show-post.component.html'
6
})
7
export class ShowPostComponent implements OnInit {
8
9
  constructor() {
10
      
11
  }
12
13
  ngOnInit(){
14
  
15
  }
16
17
}

Import the ShowPostComponent in the app.module.ts file.

1
import { ShowPostComponent } from './show-post/show-post.component';

Add ShowPostComponent in the NgModule in the app.module.ts file. 

1
import { BrowserModule } from '@angular/platform-browser';
2
import { NgModule } from '@angular/core';
3
import { ROUTING } from './app.routing';
4
import { FormsModule } from '@angular/forms';
5
import { HttpClientModule } from '@angular/common/http';
6
7
import { RootComponent } from './root/root.component';
8
import { LoginComponent } from './login/login.component';
9
import { HomeComponent } from './home/home.component';
10
import { ShowPostComponent } from './show-post/show-post.component';
11
12
@NgModule({
13
  declarations: [
14
    RootComponent,
15
    LoginComponent,
16
    HomeComponent,
17
    ShowPostComponent
18
  ],
19
  imports: [
20
    BrowserModule,
21
    ROUTING,
22
    FormsModule,
23
    HttpClientModule
24
  ],
25
  providers: [],
26
  bootstrap: [RootComponent]
27
})
28
export class AppModule { }

Modify the home.component.html file to include the ShowPostComponent selector.

1
<app-show-post></app-show-post>

Here is how the modified home.component.html file looks:

1
<header class="header clearfix">
2
    <nav>
3
        <ul class="nav nav-pills float-right">
4
            <li class="nav-item">
5
                <button type="button" class="btn btn-primary">
6
                  Home
7
                </button>
8
            </li>
9
            <li class="nav-item">
10
                <button type="button" class="btn btn-link" data-toggle="modal" data-target="#exampleModal">
11
                  Add
12
                </button>
13
            </li>
14
            <li class="nav-item">
15
                 <button type="button" class="btn btn-link">
16
                  Logout
17
                </button>
18
            </li>
19
        </ul>
20
    </nav>
21
    <h3 class="text-muted">Angular Blog App</h3>
22
</header>
23
24
<main role="main">
25
    <app-show-post></app-show-post>
26
</main>
27
28
<footer class="footer">
29
    <p>&copy; Company 2017</p>
30
</footer>

Save the above changes and refresh the client application. On signing into the application, you will be able to view the blog posts listed.

Angular Blog App - Show Post ComponentAngular Blog App - Show Post ComponentAngular Blog App - Show Post Component

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:

1
import { Injectable } from '@angular/core';
2
import { HttpClient } from '@angular/common/http';
3
4
@Injectable()
5
export class ShowPostService {
6
7
    constructor(private http: HttpClient){
8
9
	}
10
11
}

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:

1
getAllPost(){
2
	return this.http.post('/api/post/getAllPost',{})
3
}

Here is how the show-post.service.ts file looks:

1
import { Injectable } from '@angular/core';
2
import { HttpClient } from '@angular/common/http';
3
import { Post } from '../models/post.model';
4
5
@Injectable()
6
export class ShowPostService {
7
8
    constructor(private http: HttpClient){
9
10
	}
11
	
12
	getAllPost(){
13
		return this.http.post('/api/post/getAllPost',{})
14
	}
15
16
}

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:

1
const mongoose = require('mongoose');
2
const Schema = mongoose.Schema;
3
4
// create a schema

5
const postSchema = new Schema({
6
  title: { type: String, required: true },
7
  description: { type: String, required: true }
8
}, { collection : 'post' });
9
10
const Post = mongoose.model('Post', postSchema);
11
module.exports = Post;

Export the above defined post.js file in app.js.

1
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.

1
app.post('/api/post/getAllPost', (req, res) => {
2
    mongoose.connect(url, { useMongoClient: true } , function(err){
3
		if(err) throw err;
4
		console.log('connection established successfully');
5
	});
6
})

Once you have the connection established, you can use the Post model to find the list of blog posts.

1
Post.find({},[],{},(err, doc) => {
2
	if(err) throw err;
3
	console.log('result is ',doc);
4
})

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.

1
Post.find({},[],{ sort: { _id: -1 } },(err, doc) => {
2
	if(err) throw err;
3
})

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:

1
app.post('/api/post/getAllPost', (req, res) => {
2
    mongoose.connect(url, { useMongoClient: true } , function(err){
3
		if(err) throw err;
4
		Post.find({},[],{ sort: { _id: -1 } },(err, doc) => {
5
			if(err) throw err;
6
			return res.status(200).json({
7
				status: 'success',
8
				data: doc
9
			})
10
		})
11
	});
12
})

Making the API Call

In the show-post.component.ts file, define an array list for keeping the results of the API call.

1
public posts : any [];

Import the ShowPostService in the ShowPostComponent.

1
import { ShowPostService } from './show-post.service';

Add the ShowPostService as a provider to the ShowPostComponent.

1
@Component({
2
  selector: 'app-show-post',
3
  templateUrl: './show-post.component.html',
4
  styleUrls: ['./show-post.component.css'],
5
  providers: [ ShowPostService ]
6
})

Define a method called getAllPost to make a call to the service method. Here is how it looks:

1
getAllPost(){
2
  this.showPostService.getAllPost().subscribe(result => {
3
  	this.posts = result['data'];
4
  });
5
}

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.

1
ngOnInit(){
2
  this.getAllPost();
3
}

Here is how the show-post.component.ts file looks:

1
import { Component, OnInit } from '@angular/core';
2
import { ShowPostService } from './show-post.service';
3
4
@Component({
5
  selector: 'app-show-post',
6
  templateUrl: './show-post.component.html',
7
  styleUrls: ['./show-post.component.css'],
8
  providers: [ ShowPostService ]
9
})
10
export class ShowPostComponent implements OnInit {
11
12
  public posts : any [];
13
14
  constructor(private showPostService: ShowPostService) {
15
      
16
  }
17
18
  ngOnInit(){
19
  	this.getAllPost();
20
  }
21
22
  getAllPost(){
23
  	this.showPostService.getAllPost().subscribe(result => {
24
  		this.posts = result['data'];
25
  	});
26
  }
27
28
}

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:

1
mongo

Once you enter the mongo shell, check the database available in the MongoDB database.

1
show collections;

Select the blogDb database from the listed entries.

1
use blogDb

Create a collection named post.

1
db.createCollection('post')

Insert a couple of entries into the post collection.

1
db.post.insert(
2
    { title : 'TutsPlus Python Entry',
3
      description : 'Welcome to official entry of TutsPlus Python programming session'
4
    }
5
)

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:

1
<div class="list-group">
2
    <a *ngFor="let post of posts" href="#" class="list-group-item list-group-item-action flex-column align-items-start">
3
        <div class="d-flex w-100 justify-content-between">
4
            <h5 class="mb-1">{{post.title}}</h5>
5
            <small>3 days ago</small>
6
        </div>
7
        <p class="mb-1">{{post.description}}</p>
8
        <small>read more...</small>
9
    </a>
10
</div>

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.

Angular Blog App - Dynamic Blog Post ListingAngular Blog App - Dynamic Blog Post ListingAngular Blog App - Dynamic Blog Post Listing

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.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.