Angular HTTP With Observable

In this article we will discuss on how to send HTTP request using RXJs Observable. Observables are just like promises but with big difference that make them better.


Some differences between Observables & Promises given below

Observables Promises
we can canceled Observables  we can not cancelled Promises
It can handle multiple values at a time  It can not handle single value at a time.

Ability of the Observables we can easily use with real-time application. For Observables we have use RxJs. RxJs have many operator which manipulate data and emit that data.  We have mainly use Map,Take,Filter,skip,Catch operators.

Here is the example for Angular Services using Observables


/**
Perform HTTP Get Method. First we need to pass URL where it send to get data.
its return data as observable.
*/
get(url: string, options?: RequestOptionsArgs): Observable;

/**
Perform HTTP Post Method. First we need to pass URL where it send to get data.
Second parameter to pass as data.
its return data as observable.
*/
post(url: string, body: any, options?: RequestOptionsArgs): Observable;
/**
Perform Delete Using HTTP.
*/
delete(url: string, options?: RequestOptionsArgs): Observable;

In HTTP mainly PUT,POST,GET,DELETE,REQUEST,HEAD,PATCH but we have use mainly POST,GET,DELETE.
Creating Service we need import “Injectable”.


Here is the example code How services looks like.


//
// below v4 we need to import 
import { Http, Response, Headers, RequestOptions } from '@angular/http';
//Angular 4+ we need to import from common.
import { HttpClient } from '@angular/common/http';

import { Injectable }     from '@angular/core';
import {Observable} from 'rxjs/Rx';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class firstComponetService{

  // For Below V4
  url:string = '';
  constructor (private http: Http) {
   this.url = ""; //URL form where you get data
  }

  // For V4+
  constructor(private http: HttpClient) {
this.url = ""; //URL form where you get data
  }

  //Create GET method for getting data
  getData() : Observable {

         return this.http.get(this.url).map((res:Response) => res.json())
                         .catch((error:any) => Observable.throw(error.json().error || 'Server error'));

     }



}

In next article we discus on Model for the service.

Spread the love
  • 20
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •