How to call a simple http GET service in Angular 2

techie_questie picture techie_questie · Dec 12, 2016 · Viewed 10.8k times · Source

I am learning Angular 2 and I am trying to call a simple HTTP Get request on page load for the JSON data I have and manipulate that JSON on page load. Can anyone tell me with some basic example how to do that? I am seeing most of the solutions on net from Beta version.

Answer

Emu picture Emu · Dec 12, 2016

Create a service like:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/Rx';
import {Observable} from 'rxjs/Rx'

export class MyService {
  constructor(public http: Http) { }

  private extractData(res) {

    if (res.status < 200 || res.status >= 300) {
      throw new Error('Bad response status: ' + res.status);
    }

    // console.log(res.json());
    this.serviceData = (res.json());
    return this.serviceData || {};
  }

  loaddata(): Observable<any> {
    return this.http.get(this.server_url) // define a variable server_url to assign the requested url
      .map(this.extractData);
  }
}

Now in your component's ngOnInit method get the values by calling this service method.

class MyComponent{
    constructor(public _myService: MyService)
    ngOnInit(){
      this._myService.loaddata().subscribe(data => {
      // do something with the data
    })

   }
}