Angular 2 Http Cheat Sheet

A Programming › HTTP cheat sheet in English by Nathane2005

Angular 2 Http

17,582 views 4,611 downloads 17 Oct 2016 History
4.9 avg · 4 ratings

Starting Up

@NgModule({
     declarations: [],
     imports: [HttpModule],
     bootstrap: [],
     providers: []
})

Using Angular HTTP

constructor(private http: Http) {}

Http Verbs

GET
get(url: string, options?: Reques­tOp­tio­nsArgs) : Observ­abl­e<R­esp­ons­e> Performs a request with get http method.
POST
post(url: string, body: any, options?: Reques­tOp­tio­nsArgs) : Observ­abl­e<R­esp­ons­e> Performs a request with post http method.
PUT
put(url: string, body: any, options?: Reques­tOp­tio­nsArgs) : Observ­abl­e<R­esp­ons­e> Performs a request with put http method.
DELETE
delete­(url: string, options?: Reques­tOp­tio­nsArgs) : Observ­abl­e<R­esp­ons­e> Performs a request with delete http method.
PATCH
patch(url: string, body: any, options?: Reques­tOp­tio­nsArgs) : Observ­abl­e<R­esp­ons­e> Performs a request with patch http method.
HEAD
head(url: string, options?: Reques­tOp­tio­nsArgs) : Observ­abl­e<R­esp­ons­e> Performs a request with head http method.
OPTIONS
option­s(url: string, options?: Reques­tOp­tio­nsArgs) : Observ­abl­e<R­esp­ons­e> Performs a request with options http method.

Reques­tOp­tio­nsArgs


interface RequestOptionsArgs {
  url : string
  method : string|RequestMethod
  search : string|URLSearchParams
  headers : Headers
  body : any
  withCredentials : boolean
  responseType : ResponseContentType
}

Headers


class Headers {
  staticfromResponseHeaderString(headersString: string) : Headers
  constructor(headers?: Headers|{[name: string]: any})
  append(name: string, value: string) : void
  delete(name: string) : void
  forEach(fn: (values: string[], name: string, headers: Map<string, string[]>) => void) : void
  get(name: string) : string
  has(name: string) : boolean
  keys() : string[]
  set(name: string, value: string|string[]) : void
  values() : string[][]
  toJSON() : {[name: string]: any}
  getAll(name: string) : string[]
  entries()
}

Observ­ables - Flow

Observables - Flow

Sample Delegate

import { Injectable } from '@angular/core';
import {Http, Response, Headers, RequestOptions} from "@angular/http";
import 'rxjs/Rx';
import {Observable} from "rxjs";
import {Post} from "./http/post.class";


@Injectable()
export class HttpService {

  constructor(private http: Http) { }

  private requestUrl: string = 'http://localhost:4000/posts';

  //Do all methods and observable options

  getData(id : number) : Observable<Post> {
    return this.http.get(`${this.requestUrl}/${id}`)
      .map(this.mapResponse)
      .catch(this.handleError)
  }

  handleError(error: any): Observable<any> {
    console.error('An error occurred', error);
    return Observable.throw(error.json() || 'Server error');
  }

  mapResponse(response : Response) : Post {
    return response.json();
  }

  addData(body : Post) : Observable<Post> {
    let bodyString = JSON.stringify(body);
    let header = new Headers({
      'Content-Type' : 'application/json'
    });
    let options = new RequestOptions({
      headers : header
    });

    return this.http.post(`${this.requestUrl}`, bodyString, options)
      .map(this.mapResponse)
      .catch(this.handleError);
  }

  updateData(body : Post) : Observable<Post> {
    let bodyString = JSON.stringify(body);
    let header = new Headers({
      'Content-Type' : 'application/json'
    });
    let options = new RequestOptions({
      headers : header
    });

    return this.http.put(`${this.requestUrl}/${body.id}`, bodyString, options)
      .map(this.mapResponse)
      .catch(this.handleError);
  }

  deleteData(body : Post) : Observable<Post> {
    return this.http.delete(`${this.requestUrl}/${body.id}`)
      .map(this.mapResponse)
      .catch(this.handleError);
  }

}

Rx - Map

getData(id : number) : Observable<Post> {
    return this.http.get(`${this.requestUrl}/${id}`)
      .map(this.mapResponse)
      .catch(this.handleError)
  }


  mapResponse(response : Response) : Post {
    return response.json();
  }
The map() function takes in a lambda function or a reference to a function that will execute the procedure and return the mapped result.
Accepts (res : Respone) and returns a result.

Rx - catch

  getData(id : number) : Observable<Post> {
    return this.http.get(`${this.requestUrl}/${id}`)
      .map(this.mapResponse)
      .catch(this.handleError)
  }

  handleError(error: any): Observable<any> {
    console.error('An error occurred', error);
    return Observable.throw(error.json() || 'Server error');
  }
The catch reference is there to handle exceptions that are thrown. This gives you an opport­unity to handle them in a graceful manner.
All rx operations return an observ­able.

Observable - Subscribe

observ­erO­rNext
Partia­lOb­ser­ver­<T> | ((value: T) => void)
error
(error: any) => void
complete
() => void
this.s­erv­ice.ge­tDa­ta(­10).su­bsc­ribe(
(data : Post) => {
this.r­esult = data;
},
(error : any) => {
consol­e.e­rro­r(e­rror);
}
)

Reference

 private requestUrl: string = 'http://localhost:4000/posts';

  getData(id : number) : Observable<Post> {
    return this.http.get(`${this.requestUrl}/${id}`)
      .map(this.mapResponse)
      .catch(this.handleError)
  }
Using the back ticks to specify internal references ``
refere­ncing the content in ${}

Badges

Nice Cheat Sheet Good Cheat Sheet Downloaded from Unusual Locations × 3

Comments

No comments yet.

Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.