WEB DEVELOPER SITE
PYTHONJAVAPHP7
 

Angular 4 Http Service


Angular 4 is update feature Http Service will help us fetch external data, post to it.


To start using the http service, we must need to import the module in app.module.ts as listed here
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';

@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      BrowserModule,
      BrowserAnimationsModule,
      HttpModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})
export class AppModule { }

then we added http service in the app.component.ts.
import { Component } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})

export class AppComponent {
   constructor(private http: Http) { }
   ngOnInit() {
      this.http.get("http://google158.wordpress.com/users").
      map((response) ⇒ response.json()).
      subscribe((data) ⇒ console.log(data))
   }
}


We need to import http to make use of the service
import { Http } from '@angular/http';
To fetch the data, we need to use the get API available with http by using this
this.http.get();

To use the map, we need to import the this code
import 'rxjs/add/operator/map';

For the objects to be displayed in the browser, update the codes in app.component.html and app.component.ts we can do
import { Component } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   constructor(private http: Http) { }
   httpdata;
   ngOnInit() {
      this.http.get("http://jsonplaceholder.typicode.com/users").
      map(
         (response) ⇒ response.json()
      ).
      subscribe(
         (data) ⇒ {this.displaydata(data);}
      )
   }
   displaydata(data) {this.httpdata = data;}
}

for over this httpdata variable, which is done in the app.component.html file
  • Name : {{data.name}} Address: {{data.address.city}}
We have consoled the data in the browser, which is received from the http. The same is displayed in the browser console. The name from the json with id=2 is displayed in the browser.