python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 7, Interview Questions Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language
Angular 5 API call GET POST PUT and DELETE

Angular 5 API calls with HttpClient Service | Get, Post, Put and Delete

Angular 4.3 introduced a new service called HttpClient. The HttpClient Service was the replacement for the Http service from Angular 2.  The HttpClient works mostly the same as the old HTTP service. The HttpClient service is handling both single and concurrent data. Http service still works but it will be removed in a future release.
                    
Stayed Informed - HttpClient vs HttpClientModule Angular
The types of HttpClient service -
1.      HttpClient.get
2.      HttpClient.post
3.      HttpClient.put
4.      HttpClient.delete

In the below example, I will share how to create Angular 5 REST API using Angular HttpClient services and other - Installing HttpClientModule - app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule, FormGroup} from '@angular/forms';
import {RouterModule} from '@angular/router';
import {HttpClientModule} from "@angular/common/http";
//MY COMPONENTS
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { EmployeeComponent } from './employee/employee.component';

//My Services
import { AuthServiceService } from './auth-service.service';
import { AuthGuard } from './auth.guard';
import {EmployeeService} from '../app/employee.service';

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    RegisterComponent,
    EmployeeComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    RouterModule.forRoot([
      { path: '', component: AppComponent, pathMatch: 'full' },
      { path: 'register', component: RegisterComponent },
      { path: 'employee', component: EmployeeComponent},
      { path: 'login', component: LoginComponent}])
  ],
  providers: [EmployeeService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Injecting HttpClient – employee.service.ts
import { Injectable } from '@angular/core';
import {HttpClient, HttpParams, HttpHeaders} from "@angular/common/http";
import { Employee } from './employee';
import{ AppConstants} from '../app/constants'
import { constants } from 'fs';

@Injectable()
export class EmployeeService {
 
  //variable initialization
  headers : any;
  _baseURL : string;

  //constructor initialization
  constructor(private _htc:HttpClient) {
      this.headers = new HttpHeaders().set('content-type', 'application/json');
      this._baseURL = AppConstants.baseURL;
  }

  // POST employee - for creating a New employee.
  addEmployee(emp :any){
    var employee = {
        name:emp.name,
        Dep:emp.Dep,
        Des:emp.Des 
    } 
   
    return this._htc.post<Employee>(this._baseURL+'/Employees/Add', employee, (this.headers));
  }

  //PUT employee - for update employee.
  editEmployee(emp :any){
    var employee = {
        id:emp.id,
        name:emp.name,
        Dep:emp.Dep,
        Des:emp.Des 
    } 
   
    return this._htc.put<Employee>(this._baseURL+'/Employees/Edit', employee, (this.headers));
  }

  //DELETE employee - for delete employee.
  deleteEmployee(id :string){    
    return this._htc.delete<Employee>(this._baseURL+'/Employees/Delete/'+id);
  }
}

Use of Constants - constants.ts
export class AppConstants {
    public static get baseURL(): string { return "http://localhost:4200/api"; }
}

Use of Services in Components – employee.component.ts
import { Component, OnInit } from '@angular/core';
import {Employee } from '../employee'
import { Validators, FormGroup, FormControl } from '@angular/forms';
import {EmployeeService} from '../employee.service'
import { constants } from 'fs';

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

  constructor( public _empService: EmployeeService) { }
  empForm:any;

  ngOnInit() {
    this.empForm = new FormGroup({
      'name': new FormControl(this.employee.name, [Validators.required,Validators.minLength(4)]),
      'Dep': new FormControl(this.employee.Dep, [Validators.required, Validators.minLength(10)]),
      'Desc': new FormControl(this.employee.Desc, Validators.required)
    });
  }

  employee = new Employee(0,'','','');
  submitted = false;

  //Add new Employee
  onSubmit() {
    this.submitted = true;
    let isSuccess = this._empService.addEmployee(this.employee);
    if(isSuccess){
     //handle success
     console.log(isSuccess);
    }else{
      //handle errors
    }
  }
}

UI part - employee.component.html
<div class="container">
  <h1>Employee Form</h1>
  <form #empForm="ngForm" (ngSubmit)="onSubmit()">
    <div class="form-group">
      <label for="name">Name</label>
      <input type="text" class="form-control" id="name"  required [(ngModel)]="employee.name" name="name">
    </div>

    <div class="form-group">
      <label for="Dep">Department</label>
      <input type="text" class="form-control" id="Dep"  required [(ngModel)]="employee.Dep" name="Dep">
    </div>

    <div class="form-group">
      <label for="Desc">Desc</label>
      <input type="text" class="form-control" id="Desc"  required [(ngModel)]="employee.Desc" name="Desc">
    </div>

    <button type="submit" class="btn btn-success" [disabled]="!empForm.form.valid">Submit</button>
  </form>
</div>

<div [hidden]="!submitted">
  <h2 style="color:green;">Record Added Scussfully!</h2>
</div>


Result looks like –

ANIL SINGH

Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - http://code-sample.com and http://code-sample.xyz
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like
www.code-sample.com/. Powered by Blogger.
ASK Questions