Skip to content
logo
  • Home
  • What We Do
  • Portfolio
  • About Us
  • News
  • Contact
  • Home
  • What We Do
  • Portfolio
  • About Us
  • News
  • Contact
lognscreen

Creating a Blogging App Using Angular & MongoDB: Show Post

Leave a Comment / By Medianic / 14th February 2018

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.

Angular 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:

List group item heading
3 days ago

Donec 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 ago

Donec 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 ago

Donec 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

© Company 2017

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 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:

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.

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

Powered by WPeMatico

0
0
0
0
0
0
← Previous Post
Next Post →

Leave a Comment Cancel Reply

You must be logged in to post a comment.

Recent Posts

  • Website Color Schemes: 30 Best Choices for Stunning Design

    Website Color Schemes: 30 Best Choices for Stunning Design

    22nd May 2025
  • Photoshop Space Scene Tutorial: Create Surreal Designs

    Photoshop Space Scene Tutorial: Create Surreal Designs

    21st May 2025
  • WordPress Hosting Packages: Top 10 Choices for Developers

    WordPress Hosting Packages: Top 10 Choices for Developers

    21st May 2025
  • 20+ Best Free InDesign Brochure Templates for Creatives in 2025

    20+ Best Free InDesign Brochure Templates for Creatives in 2025

    21st May 2025
  • A Reader’s Question on Nested Lists

    A Reader’s Question on Nested Lists

    19th May 2025
All News

Subscribe to our Articles


Newsletter


Medianic Web Design
5.0
powered by Google
review us on
John Fegan
21:25 22 Jul 21
Professional and rapid support for the development and ongoing maintenance of our business website. Nothing too much trouble. Highly recommended.
Paul Jackson
11:24 28 Jun 21
Superb service very professional and quickvery responsive i was kept informed and consulted throughout the entire process.
See All Reviews
Trustpilot




Kate has been so helpful, patient with our constant changes and so professional in all respects. Many thanks and very done!
Club de Golf Javea
Club de Golf JaveaWebsite Redesign
Kate is the person to go to in regards to these matters. Had a lot of problems with my website, errors, payment issues and more. Every problem was resolved quickly and professionally and cannot recommend Kate's company highly enough. Personal and responsive service. 5 Stars!
WowVac Pro
WowVac ProE-Commerce Configuration
Best Developer in Spain! Outstanding web services no matter where you are in the world. Great support and attention to detail. Kate is a real life developer. She can work across multiple platforms and understands the technology your company is using on a line to line basis.
Favicon
Pure Organic CBDWeb development and support
Professional and rapid support for the development and ongoing maintenance of our business website. Nothing too much trouble. Highly recommended.
Cafeciclistalogo
Cafe CiclistaWeb maintenance
Superb service very professional and quick very responsive I was kept informed and consulted throughout the entire process.
Partnerchipz Black
Paul JacksonWeb design & Development
Kate Langshaw of Medianic is awesomely recommended by us for all your website needs. Kate translated our story and brand into an elegant, transparent and to the point representation of CaffèMilano -The Italian Coffee House.
CaffèMilano
CaffèMilanoWeb design and Development
Absolute Class service from Start to finish, nothing is too much hassle for them and will recommend to everybody looking to update or have their website designed by the Amazing Kate Langshaw
Dragon Insure
Dragon InsureWeb design and Development
I have to say that my experience with Medianic has been different to any previous. I have been constantly kept up to date, communication has been fluid, and we had no down time at all.
Dr Banuls
Dr BanulsWeb Hosting
I’m very happy about Kate’s work! Recommend her services to everybody. Looking for a good website builder/designer? Look no further and contact Medianic.
Voice Productions
Voice ProductionsWeb development
On Behalf of all at the Marina Alta Classic Car Club I would like to thank Kate for the wonderful work she did in Kick starting our Club website this year. I can highly recommend her. Thanks Kate
Marina Alta Car Club
Marina Alta Car ClubWeb Design
Excellent knowledge and service, competitive pricing too. Definitely a solid go to company. Thanks for the great results we’ve had
Jim JimneyDesign and Branding
Totally reliable, totally capable and totally delivers. I’m loving working with Kate to help grow my business. I’m full of motivation because of you Kate
Javea Blinds
Javea BlindsWeb Design
I cannot praise Medianic enough. They have built the Javea Connect website quickly and efficiently, taught and old dog new tricks and have been there for me, sometimes within minutes, when I needed help. Excellent service and very very competitively priced. Highly recommended for both website and design work. Kate is to be congratulated on such a high standard of work and customer loyalty.
Javea Connect
Javea ConnectWeb Design & Development
Medianic has done a outstanding job in creating our company website in such a short time at unbeatable prices, rovtec marine services recommended Medianic for their superior skill in Web design, thank you outstanding job!
Rovtech
RovtechWeb Design
The only thing that beat the quality of the work Medianic did for us was how quick and responsive they were whenever we had feedback or needed something extra. Would highly recommend.
Poker Encore
Poker EncoreCustom Programming

Thank you!

For your kind words...

Latest News

  • Website Color Schemes: 30 Best Choices for Stunning Design

    Website Color Schemes: 30 Best Choices for Stunning Design

    22nd May 2025
  • Photoshop Space Scene Tutorial: Create Surreal Designs

    Photoshop Space Scene Tutorial: Create Surreal Designs

    21st May 2025
  • WordPress Hosting Packages: Top 10 Choices for Developers

    WordPress Hosting Packages: Top 10 Choices for Developers

    21st May 2025

Find Medianic Web Design

Javea, Costa Blanca Alicante Spain, 03730
+34 610 151 306
info@medianic.co.uk

Follow Us

Copyright © 2025 Medianic Web Design
  • Privacy Policy
  • Terms & Conditions
  • Contact
This website uses cookies to improve your experience. Accept Read More
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT
Scroll to Top