example of http get service in angular 6 -7
We use it to make ajax calls to the server.
The Http class provides the get() method for getting a resource, post() for creating it, put() for updating it, delete() for deleting resource and head() for getting metadata regarding a resource.
Observables
- Observables is a new primitive type which acts as a blueprint for how we want to create streams, subscribe to them, react to new values, and combine streams together to build new ones.
- RxJS stands for *R*eactive E*x*tensions for *J*ava*S*cript, and its a library that gives us an implementation of Observables for JavaScript.
Subscribe()
By calling subscribe onto an observable it:
- 1. Turns the observable hot so it starts producing.
- 2. Lets us pass in a callback function so we react when anything is pushed onto the final stream in the observable chain.
Example:
Step1: Create a Service.,
ng g service httpserviceex
It will create httpserviceex.
Note : Add rxjs/Rx reference
npm install rxjs@6 rxjs-compat@6 –save
import { Injectable } from '@angular/core';
import { Http, HttpModule, Response } from '@angular/http';
import 'rxjs/Rx';
@Injectable({
providedIn: 'root'
})
export class HttpserviceexService {
constructor(private http : Http) { }
getdata()
{
return this.http.get('http://apitest.cegrajasthan.in/api/infoes/Getinfoes').map((response : Response) => response.json());
}
}
Step 2 :Create new Component
ng g c usehttpget
import { Component, OnInit } from '@angular/core';
import { HttpserviceexService } from '../httpserviceex.service';
@Component({
selector: 'app-usehttpget',
templateUrl: './usehttpget.component.html',
styleUrls: ['./usehttpget.component.css']
})
export class UsehttpgetComponent implements OnInit {
constructor(private obj : HttpserviceexService) { }
finalresult : string;
ngOnInit()
{
var data ="";
this.obj.getdata().subscribe(
datas => {for(let index = 0; index < datas.length; index++) {
data += datas[index].id+" "+ datas[index].name+ " "+ datas[index].fname +"<br/>";
// alert(data)
}
this.finalresult = data;
}
);
}
}
<p> usehttpget works! </p> <div [innerHTML] = finalresult> </div>
Step 3: Pass reference in app.component.html