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.
2 Answers
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
})
}
}
2 Comments
techie_questie
Is it always important to use .subscribe after .map()?
Emu
@techiequestie, Yes, it is important. Since the API e.g.
loaddata returns an Observable, we need to subscribe to it to actually perform the http request.To get the observable, you can follow the below example. The getStories method uses the injected HTTP service and returns an observable, which can be further used to get the response.
@Injectable()
export class StoriesService {
constructor(private http:Http,private constService :ConstantsService) { }
public getStories()
{
this.http
.get(this.constService.apiBaseUrl + "Stories/Stories")
.subscribe ((data: Response) => console.log(data));
}
}
This is simple HTTP Get Service Example.