Aug 7, 2017

Angular 2 Adding http service

Angular provides @angular/http npm package to perform http request. HttpClient is available as injectable class with all the methods to perform http request. This is from HttpClientModule.

Once you have module imported you should be able to user Http class for performing  http request. In theory you can inject this (http: HttpClient ) in your component class, but to have better separation of concern you should create injectable service and let that handle http call.

As you can see from the http api documentation , it returns Observable<Response>. You should be able to use all Observable Instance Methods on this. Refer this for list of methods which can be used on  Observable. Some of the common filter, map, catch, forEach, groupBy, merge, retry, toPromose.

Since this is based on observable, the actual http call will not happen until it has any subscriber.

Refer following for a simple service which call an http endpoint.
  
import { Observable } from 'rxjs';
import { retry } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class MyService {
  constructor(private http: HttpClient) { }
  public getData(): Observable {
    return this.http.get('someurl').map((data) => { return data.json() });
  }
}