Angular HTTP Client

In Previous topic we look into Service & Dependency Injection in Angular. In this topic we will look into Angular HTTP Client.
Before looking into the HTTP clients you have to create one angular application.
You can refer below URL's for installing for installing Nodes, visual Studio, Angular CLI and create Angular Application.

HTTP Client ➤➤

HTTP Client is a built in Service available in from '@angular/common/http' package. It uses the RxJS Observable based API's which means it returns the observable and what we need to subscribe it.

RxJS Observable ➤➤

An Observable is an object that helps to manage async code. So to use it we need observable library called RxJS(Reactive Extension for JavaScript). RxJS is a library for reactive programming using observables that makes it easier to compose async code. Angular uses observables as interface to handle the common asynchronous operations.

Let's see how to use HttpClient in an angular application. I have created one application named "SchoolManagementSystem" using above mentioned URL's. we will do registration and in return we will get userId.

After creatin the application now we will import or configure HttpClientModule
into app.module.ts (Root Module). Shown Below

After importing HttpClientModule You can directly use it in component but it is best to access it via Service. For Creating a service you can use angular cli command, In SchoolManagementSystem application I have created a service using command - "ng generate service user" which will create files user.service.ts and user.service.spec.ts.

After creation of service you have to inject HttpClient in the service.
After that we will add one method which takes registration payload as input and it will return observable.


HttpClient.post() send HTTP POST request to the endpoint and we need to subscribe to the post() method to send the request. Post method will parsed the body of the response as JSON and returns it. 
The Syntax of HTTP POST is shown blow:

   post(url: string, body: any | null, options?: {
        headers?: HttpHeaders | {
            [header: string]: string | string[];
        };
        context?: HttpContext;
        observe?: 'body';
        params?: HttpParams | {
            [param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
        };
        reportProgress?: boolean;
        responseType?: 'json';
        withCredentials?: boolean;
    }): Observable<Object>;

After this now you can subscribe this in component file, I have created registration component for registration part. You can create a component using angular cli command "ng generate component registration" this command will create 4 file i.e. registration component css, html, spec.ts and ts file. below is the code for registration.component.ts file

import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { Observable } from 'rxjs';
import { ToastService } from 'src/app/_service/toast.service';
import { UserService } from 'src/app/_service/user.service';

@Component({
  selector: 'app-registration',
  templateUrl: './registration.component.html',
  styleUrls: ['./registration.component.css']
})
export class RegistrationComponent implements OnInit {

  regForm: any = {
    name: null,
    email: null,
    password: null,
    registerAs: null
  };
  isSuccessful = false;
  isSignUpFailed = false;
  errorMessage = '';

  constructor(
    private userService: UserService,
    private toastService: ToastService
  ) { }

  ngOnInit(): void { }

  onSubmit() {
    console.log(this.regForm);
    let request = {
      userName: this.regForm.name,
      email: this.regForm.email,
      password: this.regForm.password,
      role: this.regForm.registerAs
    }
    const response: Observable<any> = this.userService.userRegistration(request);
    response.subscribe({
      next: data => {
        console.log("data" + data);
        if (data && data['status'].toLowerCase() === 'success') {
          this.isSuccessful = true;
          this.isSignUpFailed = false;
          console.log("data inside if:" + data);
          let toastObject = {
            title: "Registration Successful for (" + request.userName + ")",
            desc: "<strong>your userId : " + data['data']['userId'] + "</strong>",
          };
          this.showToastMessge(toastObject);
        } else if (data && data['status'].toLowerCase() === 'fail') {
          this.isSignUpFailed = true;
          this.errorMessage = data['data']['message'];
          let toastObject = {
            title: "Unsuccesful !",
            desc: "<strong>" + data['data']['message'] + "</strong>",
          };
          this.showToastMessge(toastObject);
        }
      },
      error: err => {

        this.isSignUpFailed = true;
      }
    });

  }
  showToastMessge(toastObject) {

    let toastObbject = {
      title: toastObject?.title,
      desc: toastObject?.desc
    };
    this.toastService.show(toastObbject);

  }

}

Below is the code for registration.component.html

<div id="reg_background" class="row">
    <div class="col-md-4 offset-md-4 col-sm-6 offset-sm-3">
        <div class="card auth">
            <div class="card-body auth-card">
                <div class="auth-avatar">
                    <img src="../../../assets/Images/user_icon.png" class="user-image">
                </div>
                <form name="form" (ngSubmit)="f.form.valid && onSubmit()" #f="ngForm" novalidate>
                    <div class="form-group">
                        <label for="name">Name : </label>
                        <input type="text" name="name" class="form-control" placeholder="Name"
                            [(ngModel)]="regForm.name" required minlength="3" maxlength="20" #name="ngModel"
                            [ngClass]="{ 'is-invalid': f.submitted && name.errors }" />

                        <div class="invalid-feedback" *ngIf="name.errors && f.submitted">
                            <div *ngIf="name.errors['required']">Name is required</div>
                            <div *ngIf="name.errors['minlength']">
                                Name must be at least 3 characters
                            </div>
                            <div *ngIf="name.errors['maxlength']">
                                Name must be at most 20 characters
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="email">Email : </label>
                        <input type="email" name="email" class="form-control" placeholder="Email"
                            [(ngModel)]="regForm.email" required email #email="ngModel"
                            [ngClass]="{ 'is-invalid': f.submitted && email.errors }" />
                        <div class="invalid-feedback" *ngIf="email.errors && f.submitted">
                            <div *ngIf="email.errors['required']">Email is required</div>
                            <div *ngIf="email.errors['email']">
                                Email must be a valid email address
                            </div>

                        </div>
                    </div>
                    <div class="form-group">
                        <label for="password">Password : </label>
                        <input type="password" name="password" class="form-control" placeholder="********"
                            [(ngModel)]="regForm.password" required minlength="6" #password="ngModel"
                            [ngClass]="{ 'is-invalid': f.submitted && password.errors }">
                        <div class="invalid-feedback" *ngIf="password.errors && f.submitted">
                            <div *ngIf="password.errors['required']">Password is required</div>
                            <div *ngIf="password.errors['minlength']">
                                Password must be at least 6 characters
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="userType">Register As : </label><br>
                        <div class="form-check form-check-inline">
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="userType" id="inlineRadio1"
                                    value="student" [(ngModel)]="regForm.registerAs" required #userType="ngModel"
                                    [ngClass]="{ 'is-invalid': f.submitted && userType.errors }">
                                <label class="form-check-label" for="student"> Student</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="userType" id="inlineRadio2"
                                    value="teacher" [(ngModel)]="regForm.registerAs" required #userType="ngModel"
                                    [ngClass]="{ 'is-invalid': f.submitted && userType.errors }">
                                <label class="form-check-label" for="teacher">Teacher</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="userType" id="inlineRadio3"
                                    value="admin" [(ngModel)]="regForm.registerAs" required #userType="ngModel"
                                    [ngClass]="{ 'is-invalid': f.submitted && userType.errors }">
                                <label class="form-check-label" for="admin">Admin</label>

                            </div>
                            <div class="invalid-feedback" *ngIf="userType.errors && f.submitted">
                                <div *ngIf="userType.errors['required']">User Type is required</div>

                            </div>
                        </div>

                    </div>
                    <div class="text-center">
                        <input type="submit" class="btn btn-my" value="Sign Up">
                    </div>

                    <div class="text-center login">
                        Already have an account ? <a routerLink="/login">Login</a> here.
                    </div>
                </form>
            </div>
        </div>
    </div>
    <app-toast></app-toast>
</div>

Below is the code for registration.component.css

#reg_background
{
 margin:0px;
 height:100%;
 width:100%;
 background:url('../../../assets/Images/reg_background.jpg') no-repeat;
 -webkit-background-size:cover;
 background-size:cover;
 min-height: 100vh;
 -moz-background-size:cover;
 background-size:cover;
}


.auth-card{
    background: #c31432;  /* fallback for old browsers */
    background: -webkit-linear-gradient(to bottom, #240b36, #c31432);  /* Chrome 10-25, Safari 5.1-6 */
    background: linear-gradient(to bottom, #240b36, #c31432); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
    border-radius: 5px;
    box-shadow: 10px 0px 30px #f7f7f7;
  }
  label{
    color: #fff;
    font-weight: 700;
  }
  .user-image{
    height: 70px;
  }
  .auth-avatar{
    text-align: center;
    margin-top: -50px;
  }
  .auth{
    margin-top: 35px;
    border: none;
    border-radius: 6px;
  }
  .btn-my{
    background-color: #d39e00;
    border-color: #d39e00;
    color: #fff;
  }
  .simple-keyboard {
    max-width: 850px;
  }

  .login{
    color: #fff;
  }
  .login a{
    color: #d39e00;
    font-weight: 600;
    text-decoration: none;
  }

Below is the code for app-routing.module.ts , I will discuss routing module later for now think it as when we put any url it will route to specific component because of this module.

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ErrorComponent } from './Component/error/error.component';
import { LoginComponent } from './Component/login/login.component';
import { RegistrationComponent } from './Component/registration/registration.component';

const routes: Routes = [
  {path : '', component : LoginComponent},
  {path : 'login', component : LoginComponent},
  {path : 'signup', component : RegistrationComponent},
  {path : '**', component : ErrorComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Once you go to localhost then you can see below page.


After filling the form and click on submit you can see our java API is getting called as shown below and its payload: Highlighted in Yellow is payload/Request and in green in the response coming from JAVA API. We can also see the data getting persisted in database.



Similarly you can make use of other HTTP method like get, delete, put and others.

Let me know for any Query.

Comments

Popular posts from this blog

Angular Observables