HOW TO BUILD A LOGIN AND SIGN UP PAGE WITH API AUTHENTICATION IN ANGULAR
Tags: javascript, typescript, angular, tutorial
Published: 2022-01-10 04:17:55


## 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](https://www.freecodecamp.org/news/what-is-an-api-in-english-please-b880a3214a82/) 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
```
  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
```
This would change our directory to myApp folder.

```
ng serve --o
```
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
```

```
ng generate component components/login-page
```

```
ng generate component components/home
```
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](https://www.smashingmagazine.com/2018/11/a-complete-guide-to-routing-in-angular/). 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:

```js
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';
```

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

```ts
const routes: Routes = [
  {path:"", redirectTo:"login", pathMatch:"full"},
  {path:"login", component:LoginPageComponent},
  {path:"signUp", component:SignUpPageComponent},
  {path:"home", component:HomeComponent},
];

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

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

```html
<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>
```
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](https://github.com/typicode/json-server). 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
```

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.

```js
{
"signupUsersList": [
    {
      "email": "bolu@gmail.com",
      "password": "1234"
    }
  ],
}
```

3 Start JSON server

```
json-server --watch db.json
```
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](https://angular.io/guide/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:

```ts
import { FormGroup, FormBuilder } from '@angular/forms';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
```
2. Call API to register users
Still inside our **sign-up-page.component.ts** let's go inside our exports and copy the following code:

```ts
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")
    })
  }

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

```html
<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>
```

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_

```ts
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
```
_Inside our exports_

```ts
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")
    })
  }
```
Let's go into our **sign-up-page.component.html** file 
we would rewrite previous code as the following:

```html
<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>
```
 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.