Consume Restful API in Angular


Hey guys, in this post we are going to see how to create an angular application that will hit the server to collect the data or to get the data from Rest API. Let’s do it step by step.
For basic program and to create components please refer our previous post, here (https://angularsixeasily.blogspot.com/2019/01/simple-first-program.html)
We already made our basic application in the previous post, So let's create the service to get the data from server/ Rest API.
Even though you are working in front end side, it is always a good thing to know how you get the data from Rest API, So let's create Rest API first.
Here we are going to use java-spring Restful Service on the server-side, which will act as a provider to angular service and then angular will be a consumer.
Before creating RestApi, first of all understand the scenario. We have to pages, that is login and register specifically login of user and registration of the user.  That’s why we are going to send and accept users information via RestApi, So create transfer object(generally we call model) to achieve the same
Create a new Dynamic Web Project and create new class User.java, which will act as a transfer object


User.java
public class User {
    
     private String userName;
    
     private String email;
    
     private String password;
    
     private String contactNo;
    
private Long address;
    
public PromesUserProfile(String userName, String email, String password, String contactNo, Long address) {
           this.userName = userName;
           this.email = email;
           this.password = password;
           this.contactNo = contactNo;
           this. address = address;
     }

     public Long getUserName() {
           return uId;
     }

     public void setUserName(String userName) {
           this.userName = userName;
     }

    

     public String getEmail() {
           return email;
     }

     public void setEmail(String email) {
           this.email = email;
     }

public Long getPassword() {
           return password;
     }

public String setPassword(String password) {
           this.password = password;
     }

     public void setContactNo(String contactNo) {
           this.contactNo = contactNo;
     }

     public String getContactNo() {
           return contactNo;
     }

}
  
This is a transfer object at the server side, we need same at front end side as well to get data, we will see that later.
Now create Restful Service.

@RestController
public class UserController {

@RequestMapping(value = "/login/user", method = RequestMethod.POST)
public User isValidUser((@RequestBody User user) {        
try {
User validUser = loginService.isValidUser(user);
if (validUser != null) {
           return validUser;
     } else {
           return null;
     }

} catch (Exception e) {
           return null;
}
}

@RequestMapping(value = "/register/user", method = RequestMethod.POST)
public Boolean registerUser((@RequestBody User user) {         
try {
Boolean isSaved = loginService.saveUser(user);
if (isSaved != null && isSaved) {
           return isSaved;
     } else {
           return false;
     }
} catch (Exception e) {
           return false;
}
}

}

We are ready with server-side application
Now to consume Restful Service, create service in angular, before that as I mentioned earlier we have to create model in angular, Actually we can access data without a model, because what we get in repose, is JSON and we can access it directly in angular but it is good practice to have a model and access data via model. That why create a model.
Command: ng generate class User
Or Shortened
Command: ng g c user

user.ts
export class user {
    userName: String;
    password: String;
    email: String;
    contactNo: String;
    address: String

    constructor() { };

    getUserName() {
        return this.userName
    }

    setUserName(userName) {
        this.userName = userName;
    }

    getEmail() {
        return this.email
    }

    setEmail(email) {
        this.email = email;
    }

    getContactNo() {
        return this.contactNo;
    }

    setContactNo(contactNo) {
        this.contactNo = contactNo;
    }

    getAddress() {
        return this.address;
    }

    setAddress(address) {
        this.address = address;
    }
}

We have just created a model now lets create service
Command: ng generate service UserService
Or shortened
Command: ng g s UserService

D:\Angular-DemoApps\Consume-RestFulApi>ng g s UserService
Your global Angular CLI version (7.1.2) is greater than your local
version (7.1.1). The local Angular CLI version is used.

To disable this warning use "ng config -g cli.warnings.versionMismatch false".
CREATE src/app/user-service.service.spec.ts (359 bytes)
CREATE src/app/user-service.service.ts (140 bytes)

Above conman will create two file
user-service.spec.ts – debugging purpose

user-service.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { user } from '../user/user';

@Injectable({
  providedIn: 'root'
})

export class UserServiceService {

  constructor(private http: HttpClient) { }

  login(user: user) {
    return this.http.post<user>('http://localhost:8080/login/user', user);
  }

  registerUser(user: user) {
    return this.http.post<Boolean>('http://localhost:8080/register/user', user);
  }
}


This is the service who is going to consume Restful API which is developed in spring.
Followings are the updated files of our previous project and also I have added the home page, which will show on the successful login of the user.

first-Page.component.ts

import { Component, OnInit, HostListener, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { user } from '../user/user';
import { UserServiceService } from '../service/user-service.service';

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

  private user = new user();
  constructor(private router: Router, private userServiceService: UserServiceService) { }

  ngOnInit() {
    console.log("user : " + user.name);
  }

  login(user: user) {
    this.userServiceService.login(user).subscribe(user => {
      if (user != undefined) {
        this.user = user;
        console.log("Login Successfull");
        localStorage.setItem("user", JSON.stringify(this.user));
        //Goto Home Page
        this.router.navigate(["/home"]);
      }
    })
  }

  registerMe() {
    this.router.navigate(["/secondpage"]);
  }
}


first-page.component.html

<div class="container">
  <form #frm="ngForm" id="frm"><br><br>
    <div class="row">
      <div class="col-lg-4"></div>
      <div class="col-lg-6">
        <h3>Login</h3>
        <table>
          <thead>
            <th>
              Login Name
            </th>
            <th>
              <input class="form-control" type="text" [(ngModel)]="user.userName"                      name="userName" required>
            </th>
          </thead>
          <tbody>
            <tr>
              <th>
                Password
              </th>
              <td><input class="form-control" type="password"                          [(ngModel)]="user.password" name="password">
      </td>
            </tr>
            <tr>
              <td>
              </td>
              <td>
                <button class="btn btn-primary"                                                             (click)="login();">Login</button>&nbsp;
                <button class="btn btn-light" (click)="registerMe();">Register                              Me</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </form>
</div>

second-page.component.html
<br><br>
<div class="row">
  <div class="col-lg-4"></div>
  <div class="col-lg-6">
    <form action="" #frm="ngForm">
      <h3>Registration</h3>
      <table>
        <tr>
          <td>User name</td>
          <td><input [(ngModel)]="user.userName" class="form-control" type="text"                 name="userName"></td>
        </tr>
        <tr>
          <td>password</td>
          <td><input [(ngModel)]="user.password" class="form-control"                             type="password" name="password"></td>
        </tr>
        <tr>
          <td>confirm password</td>
          <td><input class="form-control" type="password" name="password"></td>
        </tr>
        <tr>
          <td>email</td>
          <td><input [(ngModel)]="user.email" class="form-control" type="text"                          name="email"></td>
        </tr>
        <tr>
          <td>contact No</td>
          <td><input [(ngModel)]="user.contactNo" class="form-control"                            type="text" name="contactNo"></td>
        </tr>
        <tr>
          <td>address</td>
          <td><input [(ngModel)]="user.address" class="form-control" type="text"                        name="address"></td>
        </tr>
        <tr>
          <td></td>
          <td><button class="btn btn-light"                       (click)="gotoLogin()">Cancel</button>&nbsp;<button c                                class="btn btn-primary"                                                          (click)="saveData()">save</button></td>
        </tr>
      </table>
    </form>
  </div>
</div>


second-page.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { user } from '../user/user';
import { UserServiceService } from '../service/user-service.service';

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

  private user = new user();

  constructor(private router: Router, private userServiceService: UserServiceService) { }

  ngOnInit() {
  }

  gotoLogin() {
    this.router.navigate(['/firstpage']);
  }

  saveData() {
    alert('User data saved successfully');
    this.router.navigate(['/firstpage']);
  }

  registerUser() {
    this.userServiceService.registerUser(this.user).subscribe(response => {
      if (response == true) {
        console.log("user registered successfully");
        this.gotoLogin();
      }
    })
  }
}


homepage.component.ts

import { Component, OnInit } from '@angular/core';
import { user } from '../user/user';

@Component({
  selector: 'app-homepage',
  templateUrl: './homepage.component.html',
  styleUrls: ['./homepage.component.css']
})
export class HomepageComponent implements OnInit {
  private user: user;
  constructor() { }

  ngOnInit() {
    this.user = JSON.parse(localStorage.getItem("user"));
  }

}



homepage.component.html

<p>
  welcome {{user}}
</p>

Yea… Done
Now we are learned how to consume Restful API using angular.


Comments