Advertisement
  1. Code
  2. JavaScript
  3. Angular

Creating a Blogging App Using Angular & MongoDB: Home

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: Login
Creating a Blogging App Using Angular & MongoDB: Show Post

In the first part of the tutorial series, you saw how to get started with creating an Angular web app. You learnt how to set up the application and created the Login component.

In this part of the series, you'll move further and write down the REST API required for interacting with the MongoDB bank end. You'll also create the Home component which will be displayed after the user has logged in successfully.

Getting Started

Let's get started by cloning the source code from the first part of the tutorial series.

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

Navigate to the project directory and install the required dependencies.

1
cd AngularBlogApp-Home/client
2
npm install

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

1
npm start

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

Creating the Login REST API

Inside the project folder AngularBlogApp-Home, create another folder called server. You'll be writing the REST APIs using Node.js.

Navigate to the server folder and initialize the project.

1
cd server
2
npm init

Enter the required details and you should have the project initialized.

You'll be using the Express framework for creating the server. Install Express using the following command:

1
npm install express --save

Once you have Express installed, create a file called app.js. This will be the root file for your Node.js server.

Here is how the app.js file looks:

1
const express = require('express')
2
const app = express()
3
4
app.get('/api/user/login', (req, res) => {
5
    res.send('Hello World!')
6
})
7
8
app.listen(3000, () => console.log('blog server running on port 3000!'))

As seen in the above code, you imported express into app.js. Using express, you created an application app.

Using app, you exposed an endpoint /api/user/login which will display a message. Start the Node.js server using the following command:

1
node app.js

Point your browser to http://localhost:3000/api/user/login and you should have the message displayed.

You'll be making a POST request from the Angular service to the server with the username and password parameters. So you need to parse the request parameters.

Install body-parser, which is Node.js body-parsing middleware to parse request parameters.

1
npm install body-parser --save

Once you have it installed, import it in app.js .

1
const bodyParser = require('body-parser')

Add the following code to the app.js file.

1
app.use(bodyParser.json())
2
app.use(bodyParser.urlencoded({ extended : false}))

The above two body-parser options return the middleware that only parses json and urlencoded bodies and only looks at requests where the Content-Type header matches the type option.

You'll be using Mongoose to interact with MongoDB from Node.js. So install Mongoose using Node Package Manager (npm).

1
npm install mongoose --save

Once you have mongoose installed, import it in app.js.

1
const mongoose = require('mongoose');

Define the MongoDB database URL in app.js.

1
const url = 'mongodb://localhost/blogDb';

Let's use Mongoose to connect to the MongoDB database. Here is how it looks:

1
app.post('/api/user/login', (req, res) => {
2
    mongoose.connect(url, function(err){
3
		if(err) throw err;
4
		console.log('connected successfully, username is ',req.body.username,' password is ',req.body.password);
5
	});
6
})

If the connection is established, the message gets logged along with the username and password.

Here is how the app.js file looks:

1
const express = require('express')
2
const bodyParser = require('body-parser')
3
const app = express()
4
const mongoose = require('mongoose');
5
const url = 'mongodb://localhost/blogDb';
6
7
app.use(bodyParser.json())
8
app.use(bodyParser.urlencoded({ extended : false}))
9
10
app.post('/api/user/login', (req, res) => {
11
    mongoose.connect(url, function(err){
12
    	if(err) throw err;
13
		console.log('connected successfully, username is ',req.body.username,' password is ',req.body.password);
14
	});
15
})
16
17
app.listen(3000, () => console.log('blog server running on port 3000!'))

Restart the Node server using the following command:

1
node app.js

To connect to the Node server from the Angular application, you need to set the proxy. Create a file called proxy.json inside the client/src folder. Here is how it looks:

1
{
2
    "/api/*": {
3
		"target": "http://localhost:3000",
4
		"secure": "false"
5
	}
6
}

Modify the client package.json file to start the application using the proxy file.

1
"start": "ng serve --proxy-config proxy.json"

Save the changes and start the client server.

1
npm start

Point your browser to http://localhost:4200 and enter the username and password. Click the sign in button and you should have the parameters logged in the Node console.

Validating the User Login

To interact with MongoDB using Mongoose, you need to define a schema and create a model. Inside the server folder, create a folder called model.

Create a file called user.js inside the model folder. Add the following code to the user.js file:

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

5
const userSchema = new Schema({
6
  username: { type: String, required: true, unique: true },
7
  password: { type: String, required: true },
8
  name: { type: String }
9
}, { collection : 'user' });
10
11
const User = mongoose.model('User', userSchema);
12
13
module.exports = User;

As seen in the above code, you imported mongoose into user.js. You created a userSchema using the mongoose schema and created the User model using the mongoose model.

Import the user.js file inside the app.js file.

1
const User = require('./model/user');

Before querying the MongoDB user collection, you need to create the collection. Go to the MongoDB shell by typing mongo. Create the collection user using the following command:

1
db.createCollection('user')

Insert a record which you'll be querying against.

1
 db.user.insert({
2
     name: 'roy agasthyan',
3
     username: 'roy',
4
     password: '123'
5
 })

Now, once mongoose gets connected to MongoDB, you'll find the record from the database using the username and password passed in. Here is how the API looks:

1
app.post('/api/user/login', (req, res) => {
2
    mongoose.connect(url,{ useMongoClient: true }, function(err){
3
		if(err) throw err;
4
		User.find({
5
			username : req.body.username, password : req.body.password
6
		}, function(err, user){
7
			if(err) throw err;
8
			if(user.length === 1){	
9
				return res.status(200).json({
10
					status: 'success',
11
					data: user
12
				})
13
			} else {
14
				return res.status(200).json({
15
					status: 'fail',
16
					message: 'Login Failed'
17
				})
18
			}
19
			
20
		})
21
	});
22
})

As seen in the above code, once you receive a response from the database, you return the same to the client side.

Save the above changes and try running the client and server. Enter the username as roy and password as 123 and you should be able to view the result in the browser console.

Redirecting to the Home Component

Once the user has been validated successfully, you need to redirect the user to the Home component. So let's start by creating the Home component. 

Create a folder called Home inside the src/app folder. Create a file called home.component.html and add the following HTML code:

1
<header class="header clearfix">
2
    <nav>
3
        <ul class="nav nav-pills float-right">
4
            <li class="nav-item">
5
                <a class="nav-link active" href="#">Home <span class="sr-only">(current)</span></a>
6
            </li>
7
            <li class="nav-item">
8
                <a class="nav-link" href="#">Add</a>
9
            </li>
10
            <li class="nav-item">
11
                <a class="nav-link" href="#">Logout</a>
12
            </li>
13
        </ul>
14
    </nav>
15
    <h3 class="text-muted">Angular Blog App</h3>
16
</header>
17
18
<main role="main">
19
20
    <div class="jumbotron">
21
        <h1 class="display-3">Lorem ipsum</h1>
22
        <p class="lead">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
23
        <p><a class="btn btn-lg btn-success" href="#" role="button">Read More ...</a></p>
24
    </div>
25
26
    <div class="row marketing">
27
        <div class="col-lg-6">
28
            <h4>Subheading</h4>
29
            <p>Donec id elit non mi porta gravida at eget metus. Maecenas faucibus mollis interdum.</p>
30
31
            <h4>Subheading</h4>
32
            <p>Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Cras mattis consectetur purus sit amet fermentum.</p>
33
34
            <h4>Subheading</h4>
35
            <p>Maecenas sed diam eget risus varius blandit sit amet non magna.</p>
36
        </div>
37
38
        <div class="col-lg-6">
39
            <h4>Subheading</h4>
40
            <p>Donec id elit non mi porta gravida at eget metus. Maecenas faucibus mollis interdum.</p>
41
42
            <h4>Subheading</h4>
43
            <p>Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Cras mattis consectetur purus sit amet fermentum.</p>
44
45
            <h4>Subheading</h4>
46
            <p>Maecenas sed diam eget risus varius blandit sit amet non magna.</p>
47
        </div>
48
    </div>
49
50
</main>
51
52
<footer class="footer">
53
    <p>&copy; Company 2017</p>
54
</footer>

Create a file called home.component.css and add the following CSS style:

1
.header,
2
.marketing,
3
.footer {
4
  padding-right: 1rem;
5
  padding-left: 1rem;
6
}
7
8
/* Custom page header */
9
.header {
10
  padding-bottom: 1rem;
11
  border-bottom: .05rem solid #e5e5e5;
12
}
13
14
.header h3 {
15
  margin-top: 0;
16
  margin-bottom: 0;
17
  line-height: 3rem;
18
}
19
20
/* Custom page footer */
21
.footer {
22
  padding-top: 1.5rem;
23
  color: #777;
24
  border-top: .05rem solid #e5e5e5;
25
}
26
27
/* Customize container */
28
@media (min-width: 48em) {
29
  .container {
30
    max-width: 46rem;
31
  }
32
}
33
.container-narrow > hr {
34
  margin: 2rem 0;
35
}
36
37
/* Main marketing message and sign up button */
38
.jumbotron {
39
  text-align: center;
40
  border-bottom: .05rem solid #e5e5e5;
41
}
42
.jumbotron .btn {
43
  padding: .75rem 1.5rem;
44
  font-size: 1.5rem;
45
}
46
47
/* Supporting marketing content */
48
.marketing {
49
  margin: 3rem 0;
50
}
51
.marketing p + h4 {
52
  margin-top: 1.5rem;
53
}
54
55
/* Responsive: Portrait tablets and up */
56
@media screen and (min-width: 48em) {
57
  /* Remove the padding we set earlier */
58
  .header,
59
  .marketing,
60
  .footer {
61
    padding-right: 0;
62
    padding-left: 0;
63
  }
64
65
  /* Space out the masthead */
66
  .header {
67
    margin-bottom: 2rem;
68
  }
69
70
  .jumbotron {
71
    border-bottom: 0;
72
  }
73
}

Create the component file called home.component.ts and add the following code:

1
import { Component } from '@angular/core';
2
3
@Component({
4
  selector: 'app-home',
5
  templateUrl: './home.component.html',
6
  styleUrls: ['./home.component.css']
7
})
8
export class HomeComponent {
9
  
10
}

As seen in the above code, you just created the HomeComponent using the @Component decorator and specifying the selector, templateUrl, and styleUrls

Add the HomeComponent to the NgModules in app.module.ts.

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
11
12
@NgModule({
13
  declarations: [
14
      RootComponent,
15
    LoginComponent,
16
    HomeComponent
17
  ],
18
  imports: [
19
    BrowserModule,
20
    ROUTING,
21
    FormsModule,
22
    HttpClientModule
23
  ],
24
  providers: [],
25
  bootstrap: [RootComponent]
26
})
27
export class AppModule { }

Import the HomeComponent in the app.routing.ts and define a route for home.

1
import { RouterModule, Routes } from '@angular/router';
2
import { ModuleWithProviders } from '@angular/core/src/metadata/ng_module';
3
4
import { LoginComponent } from './login/login.component';
5
import { HomeComponent } from './home/home.component';
6
7
export const AppRoutes: Routes = [
8
    { path: '', component: LoginComponent },
9
	{ path: 'home', component: HomeComponent }
10
];
11
12
export const ROUTING: ModuleWithProviders = RouterModule.forRoot(AppRoutes);

In the validateLogin method in the login.component.ts file, on successful validation redirect the user to the HomeComponent. To redirect, you need to import the Angular Router.

1
import { Router } from '@angular/router';

If the response from the API call is a success, you'll navigate to the HomeComponent using the Angular Router.

1
if(result['status'] === 'success') {
2
  this.router.navigate(['/home']);
3
} else {
4
  alert('Wrong username password');
5
}

Here is how the login.component.ts file looks:

1
import { Component } from '@angular/core';
2
import { LoginService } from './login.service';
3
import { User } from '../models/user.model';
4
import { Router } from '@angular/router';
5
6
@Component({
7
  selector: 'app-login',
8
  templateUrl: './login.component.html',
9
  styleUrls: ['./login.component.css'],
10
  providers: [ LoginService ]
11
})
12
export class LoginComponent {
13
14
  public user : User;
15
16
  constructor(private loginService: LoginService, private router: Router) {
17
      this.user = new User();
18
  }
19
20
  validateLogin() {
21
  	if(this.user.username && this.user.password) {
22
  		this.loginService.validateLogin(this.user).subscribe(result => {
23
        console.log('result is ', result);
24
        if(result['status'] === 'success') {
25
          this.router.navigate(['/home']);
26
        } else {
27
          alert('Wrong username password');
28
        }
29
        
30
      }, error => {
31
        console.log('error is ', error);
32
      });
33
  	} else {
34
  		alert('enter user name and password');
35
  	}
36
  }
37
38
}

Save the above changes and restart the server. Sign in to the application using the existing username and password, and you will be redirected to the HomeComponent.

Angular Blog App Home ComponentAngular Blog App Home ComponentAngular Blog App Home Component

Wrapping It Up

In this tutorial, you saw how to write the REST API endpoint for user sign-in. You learnt how to use Mongoose to interact with MongoDB from Node. After successful validation, you saw how to use Angular Router for navigating to the HomeComponent.

How was your experience learning to write an Angular application and its back end? Do let us know your thoughts and suggestions in the comments below.

Source code from this tutorial is available on GitHub.

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.