Web
Analytics
angular 4 http post services using web api example | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

http service example

import { Injectable } from '@angular/core';
import { Http ,Response , Headers} from '@angular/http';


@Injectable()
export class HttpserviceexService {

  constructor(public _http: Http) { }
  getdata()
  {
    // return this._http.get('https://test-a8c40.firebaseio.com/');
    return this._http.get('http://apitest.cegrajasthan.org/api/Employees').map((response: Response) => response.json());
  
  }
  senddata(user: any)
{
  const body = JSON.stringify(user);
  const header = new Headers();
  header.append("Content-Type","application/json");
  return this._http.post('http://apitest.cegrajasthan.org/api/Employees', body ,{ headers: header }).map((data: Response) => data.json() );
  
}

  }
  
  

 



Http Component

import { Component, OnInit } from '@angular/core';
import { Response } from '@angular/http';
import { HttpserviceexService } from '../httpserviceex.service';
import 'rxjs/Rx'; 


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

  constructor(private service: HttpserviceexService) { }

  ngOnInit() {
   /* this.service.getdata().subscribe(
      datas => console.log(datas.json())
    ); */
    this.service.getdata().subscribe(
      datas => console.log(datas)
    );
    
  

  }
  subdata(EmpName: string , Salary: string , Address: string)
    {
      this.service.senddata({EmpName: EmpName, Salary: Salary, Address: Address}).subscribe( data => console.log(data));
    }

}

Http Component (HTML)

<p>
  httpex works!
</p>
<input type="text" #EmpName />
<input type="text" #Salary />
<input type="text" #Address />
<button (click)="subdata(EmpName.value, Salary.value, Address.value)">Save Data</button>