DEV Community

Bima
Bima

Posted on • Edited on

HOW TO BUILD A LOGIN AND SIGN UP PAGE WITH API AUTHENTICATION IN ANGULAR

Introduction

Login and sign-up pages are used to control some aspects of a website's user interactions. In this article, we'll go over how to use an API to authenticate a login and sign-up page in Angular.

Learning Objectives

By the end of this article, we should be able to:

  • Perform basic route configurations in angular.

  • Call an API to register users (sign-up).

  • Call an API to login users.

  • Create and make use of JSON server.

    We will make use of JSON server as our fake backend in this
    article

Let's get started and walk through the steps to archiving this article's learning objectives.

1. Setting up/installing Angular app

A running angular app must be created before beginning work on the login or sign-up forms. This can be accomplished by executing the following commands:

ng new myApp

 // ? Would you like to add Angular routing? Yes
 // ? Which stylesheet format would you like to use? CSS
Enter fullscreen mode Exit fullscreen mode

All of our routing configuration would need to be defined in
our
angular project's app-routing.module.ts file. Angular CLI
will add the app-routing.module.ts file to our Angular
project if we answer "YES" to the question "Would you like
to add Angular routing?
".

cd myApp
Enter fullscreen mode Exit fullscreen mode

This would change our directory to myApp folder.

ng serve --o
Enter fullscreen mode Exit fullscreen mode

This would serve and open our Angular project on http://localhost:4200 by default. This way we can now view our project.

2. Generating components

Angular applications are composed of components, which serve as the foundation for angular projects or applications. We would create or generate three (3) components, which are as follows:

  • Sign-up component
  • Login component
  • Home page component

The following commands must be executed to generate the required components:

ng generate component components/signup-up-page
Enter fullscreen mode Exit fullscreen mode
ng generate component components/login-page
Enter fullscreen mode Exit fullscreen mode
ng generate component components/home
Enter fullscreen mode Exit fullscreen mode

The commands above would generate our required component.

3. Routing And Route Configuration

Navigation between our components or pages would be possible thanks to routing and route configuration. You can learn more about angular routing Here. The steps to accomplishing this, however, are as follows:

  • Go to the app.component.html file, delete everything in it (for newly installed projects only), and add
    <router-outlet></router-outlet>

  • Go to the app-routing.module.ts file, import all of our generated components in it.
    Example:

import { LoginPageComponent } from './components/login-page/login-page.component';
import { SignUpPageComponent } from    './components/sign-up-page/sign-up-page.component';
import { HomeComponent } from './components/home/home.component';
Enter fullscreen mode Exit fullscreen mode
  • Still in the app-routing.module.ts file , we would go to our routes array and, define our path of our route using our generated Angular components. Here in our path: ".." we would insert our route name. Example:
const routes: Routes = [
  {path:"", redirectTo:"login", pathMatch:"full"},
  {path:"login", component:LoginPageComponent},
  {path:"signUp", component:SignUpPageComponent},
  {path:"home", component:HomeComponent},
];

Enter fullscreen mode Exit fullscreen mode

With the above configuration, our angular application would default to displaying the login component and other components when their pathnames (e.g., /login) are called.

4. Building a simple Login and Sign-Up form

We would create our login and sign-up forms here. To begin, navigate to our login-page.component.html file and copy the following code:

<div>
    <h1>Hi Welcome Back</h1>
     <h3>Login Here</h3>
      <form>
        <div>
          <label for="email">Email</label>
          <input  required  type="text">
          <label for="password">Password</label>
          <input  type="password">
        </div>
        <button>Submit</button>
        <span>Don't have an account? 
        <a routerLink="/signUp">signUp</a></span>
      </form>
  </div>
Enter fullscreen mode Exit fullscreen mode

Now that our login page is complete (we can add our desired stylings), let's move on to our sign-up-page.component.html file and copy the following code:

<div>
   <h1>Hello Welcome </h1>
     <h3>Create An Account</h3>
      <form>
        <div>
          <label for="email">Email</label>
          <input  required  type="text">
          <label for="password">Password</label>
          <input  type="password">
        </div>
        <button>Submit</button>
        <span>Already have an account? 
        <a routerLink="/login">signUp</a></span>
      </form>
  </div>
Enter fullscreen mode Exit fullscreen mode

With this, we have gotten our login and sign-up form ready.

5. Setting up JSON server

In a matter of seconds, JSON server creates a rest API with no code, and we can access the full documentation HERE. This would serve as our fake backend, allowing our application to function as if it had a real backend. Let's get started with our setup by going through the steps below:

1 Install JSON server

npm install -g json-server
Enter fullscreen mode Exit fullscreen mode

2 Create db.json file

Let's create a db.json file with some data
We will create a new file inside myApp folder in our project and name it db.json. We would as well copy some data in it.

{
"signupUsersList": [
    {
      "email": "bolu@gmail.com",
      "password": "1234"
    }
  ],
}
Enter fullscreen mode Exit fullscreen mode

3 Start JSON server

json-server --watch db.json
Enter fullscreen mode Exit fullscreen mode

Now let us open http://localhost:3000/signupUsersList(would serve as our API link), we would see the data we added previously. This way we have successfully gotten our JSON server up and running.

6. Making API calls for authentication

To begin, we would need to make a post request in our sign-up form in order to register our users, followed by a get request for validation and authentication. We will be working with REACTIVE FORMS in angular. Let's follow the steps below to get started:

  • Call API to register users
  1. Import necessary modules Let's go to our sign-up-page.component.ts file and copy the following:
import { FormGroup, FormBuilder } from '@angular/forms';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
Enter fullscreen mode Exit fullscreen mode
  1. Call API to register users Still inside our sign-up-page.component.ts let's go inside our exports and copy the following code:
public signUpForm !: FormGroup
  constructor(private formBuilder: FormBuilder, private http: HttpClient, private router: Router) { }

  ngOnInit(): void {
    this.signUpForm = this.formBuilder.group({
      email: [""],
      password: [""]
    })
  }

  signUp(){
    this.http.post<any>("http://localhost:3000/signupUsersList",this.signUpForm.value)
    .subscribe(res=>{
      alert('SIGNIN SUCCESFUL');
      this.signUpForm.reset()
      this.router.navigate(["login"])
    },err=>{
      alert("Something went wrong")
    })
  }

Enter fullscreen mode Exit fullscreen mode

Let's go into our sign-up-page.component.html file to implement our formGroup in our form tag, formControlName in our input tags and signUp function.
we would simply rewrite previous code as the following:

<div>
   <h1>Hello Welcome </h1>
    <h3>Create An Account</h3>
      <form [formGroup]="signUpForm" (ngSubmit)="signUp()">
        <div>
          <label for="email">Email</label>
          <input formControlName="email"  type="email"  required>
          <label for="password">Password</label>
          <input formControlName="password"  type="password">
        </div>
        <button>Submit</button>
        <span>Already have an account? 
        <a routerLink="/login">signUp</a></span>
      </form>
  </div>
Enter fullscreen mode Exit fullscreen mode

The code blocks above would retrieve all of our formGroup's input field values, store them in our db.json file with the help of our JSON server, and navigate our page to our login page.

Cheers!! We were able to successfully register our users by making an API call.

  • Call API to login users Now let's go into our login-page.component.ts file and follow the steps below:

Import necessary modules

import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
Enter fullscreen mode Exit fullscreen mode

Inside our exports

public loginForm!: FormGroup

  constructor(private formbuilder: FormBuilder,private http: HttpClient, private router: Router) { }

  ngOnInit(): void {
    this.loginForm = this.formbuilder.group({
      email: [''],
      password: ['', Validators.required]
    })
  }
  login(){
    this.http.get<any>("http://localhost:3000/signupUsersList")
    .subscribe(res=>{
      const user = res.find((a:any)=>{
        return a.email === this.loginForm.value.email && a.password === this.loginForm.value.password 
      });
      if(user){
        alert('Login Succesful');
        this.loginForm.reset()
      this.router.navigate(["home"])
      }else{
        alert("user not found")
      }
    },err=>{
      alert("Something went wrong")
    })
  }
Enter fullscreen mode Exit fullscreen mode

Let's go into our sign-up-page.component.html file
we would rewrite previous code as the following:

<div>
    <h1>Hi Welcome Back</h1>
     <h3>Login Here</h3>
      <form  [formGroup]="loginForm" (ngSubmit)="login()">
        <div>
          <label for="email">Email</label>
          <input formControlName="email"  required  type="email">
          <label for="password">Password</label>
          <input formControlName="password"  type="password">
        </div>
        <button>Submit</button>
        <span>Don't have an account? 
        <a routerLink="/signUp">signUp</a></span>
      </form>
  </div>
Enter fullscreen mode Exit fullscreen mode

The code blocks above would retrieve all of our formGroup's input field values, validate them against the data in our db.json file, and navigate our page to our home page using our JSON server.
Cheers!! We successfully used an API call to authenticate our users.

Conclusion

Finally, we went through the process of "How to build a login and sign-up page in Angular," where we learned how to perform basic routing in angular, set up and use a JSON server, and login and sign-up our users using api calls.

Top comments (3)

Collapse
 
olanetsoft profile image
Idris Olubisiđź’ˇ

@olabima_ Awesome post. Do you mind rewriting your conclusion to capture the whole content in summary?

Collapse
 
olabima_ profile image
Bima

Okay, I'll make the necessary changes. Thanks.

Collapse
 
schmuerzuu profile image
ga gugu • Edited

wonderful post but would it be possible for you to upload the whole project in a zip file or something