HTTP Module

  • We use HTTP Module to get data from remote service
  • Load Http module from the angular 2 bundle in your html file.
  • The response from service is returned in form of an observable of type Response.
    • We can then convert this response to json
  • We create a service which uses the Http module to fetch data and converts to json.
    • This service is injectable in components so we need to annotate it with @Injectable decorator
    • We must inject Http module in service constructor.
  • In the component providers we need to add service as well as HTTP_Providers as providers for Http Service.
    • Since Http Service is used by our service we must include it in our component providers.
  • We use http.get method as shown to get response.

 import {Component, Input, Injectable} from 'angular2/core';  
 import {bootstrap} from 'angular2/platform/browser';  
 import { Observable } from 'rxjs/Observable';  
 import {Response,Http, HTTP_PROVIDERS} from 'angular2/http';  
 @Injectable()  
 class StudentSvc {  
 constructor(private http: Http){}  
 getStudents(): Observable<Response> {  
  return this.http.get('https://reqres.in/api/users');  
 }  
 }  
 /**  
  * Define the Component. 1 b  
  */  
 @Component({  
  selector: 'app',  
  templateUrl : 'templates/app.tpl.html',  
  providers: [HTTP_PROVIDERS,StudentSvc]  
 })  
 class StarterTemplate {  
  private name: string;  
  private students:Observable<Response>;  
  constructor (studentSvc: StudentSvc) {  
   this.name = 'Http Service Example';  
   studentSvc.getStudents().subscribe((resp)=> {  
    this.students = resp.json().data;  
   });  
  }  
 }  
 /**  
  * Bootstrap the app with `StarterTemplate`.  
  */  
 bootstrap(StarterTemplate, []);  
s

No comments:

Post a Comment