http communication in angular 2.0

Post on 16-Apr-2017

1.978 Views

Category:

Software

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Angular 2HTTP Communication

Eyal Vardi

Site: http://ng-course.org

Blog: eyalVardi.wordpress.com

Agenda Http Modules Enable RxJS Operators Http API’s Http Default Options Catch Operator JSON Web Token (JWT) Communication with JSONP Http Internal

Http Modulesimport { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { HttpModule, JsonpModule } from '@angular/http';

import { AppComponent } from './app.component';

@NgModule({ imports: [ BrowserModule, HttpModule, JsonpModule ], declarations: [AppComponent], bootstrap : [AppComponent]})export class AppModule { }

Imports the HttpModules

HTTP_PROVIDERS Provides a basic set of injectables to use

the Http service in any application.

The providers included in HttpModule: Http XHRBackend BrowserXHR - Private factory to create XMLHttpRequest

instances RequestOptions - Bound to BaseRequestOptions class ResponseOptions - Bound to BaseResponseOptions class

Enable RxJS Operators The RxJS library is quite large. It's up to us to add the operators we

need.// Add map operatorimport 'rxjs/add/operator/map';

// Add all operators to Observableimport 'rxjs/Rx';

Http Class Performs http requests using

`XMLHttpRequest` as the default backend.

Http is available as an injectable class. Calling request returns an Observable

which will emit a single Response when a response is received.

UserProxy Class Demoimport {Injectable} from '@angular/core';import {Http} from '@angular/http';import 'rxjs/Rx';

@Injectable()export class UserProxy{ constructor(private http :Http){} load(){ return this.http .get('http://api.randomuser.me/?results=10') .map(res =>res.json()) .map(res => res.results ) .map(results => { var users = []; results.forEach((i) =>{users.push(i.user)}) return users; }); }}

returnobservabl

e

Load Rx library

Http Methods request(url, options) get (url, options) delete (url, options) head (url, options) Option (url, options)

post (url, body, options) put (url, body, options) patch(url, body, options)

Http Default Options (RequestOptions) Creates a request options object to be

optionally provided when instantiating a Request.class MyOptions extends BaseRequestOptions { search: string = 'coreTeam=true';}

@NgModule({ ... provides:[{

provide : RequestOptions,

useClass : MyOptions

}]})export class AppModule{}

Catch Operator Reacts to the error case of an

Observable.  We need to return a new Observable to

continue with. export class UserProxy{ constructor(private http :Http){} load(){ return this.http .get('http://api.randomuser.me/10') .map(res =>res.json())

.catch(this.logAndPassOn);}private logAndPassOn (error: Error) { console.error(error); return Observable.throw(error);}

JSON Web Token For Examplelet headers = new Headers();

headers.append('Authorization', `Bearer ${token}`);

http.get(`${base}/api/users`, new

RequestOptions({headers}))

.subscribe(response => {

// will return the users visible

// for the authenticated user

users = response.json();

});

Communication with JSONP Angular provides us with a Jsonp services

which has the same API surface as the Http.

Only difference that it restricts us to use GET requests only.

In order to use the Jsonp service we have to specify the JsonpModule.

JSONP Demo@Injectable()export class WikipediaService { constructor(private jsonp: Jsonp) { }

search(term: string) { var params = new URLSearchParams(); params.set('search', term); params.set('action', 'opensearch'); params.set('action', 'opensearch'); params.set('callback', 'jSONP_CALLBACK');

return this.jsonp .get('http://.wikipedia.org/api.php', { search:

params }) .map(request => request.json()[1]); }}

HTTP Internal

Make Request All the methods of Http call to HttpRequest

function. See get method for example:

get( url : string,

options?: RequestOptionsArgs):

Observable<Response> { return httpRequest( this._backend, new Request(mergeOptions( this._defaultOptions,

options, RequestMethod.Get,

url))); }

get( url : string,

options?: RequestOptionsArgs):

Observable<Response> { return httpRequest( this._backend, new Request(mergeOptions( this._defaultOptions,

options, RequestMethod.Get,

url))); }

interface RequestOptionsArgs { url? : string; method? : string |

RequestMethod; search? : string |

URLSearchParams; headers?: Headers; body? : string;}

HttpRequest Functionfunction httpRequest( backend: ConnectionBackend,

request: Request):

Observable<Response> {

return backend.createConnection(request).response;}

export abstract class ConnectionBackend {

abstract createConnection(request: any): Connection;

}

export abstract class Connection { readyState: ReadyState; request: Request; response: any;

}

XHRBackend Classexport class XHRBackend implements ConnectionBackend { constructor( private _browserXHR: BrowserXhr,

private _baseResponseOptions:

ResponseOptions) {}

createConnection(request: Request): XHRConnection { return

new XHRConnection( request,

this._browserXHR,

this._baseResponseOptions ); }}

XHRConnection Classexport class XHRConnection implements Connection { request: Request; response: Observable<Response>; readyState: ReadyState;

constructor( req: Request , browserXHR: BrowserXhr,

baseResponseOptions?: ResponseOptions) {

this.request = req; this.response = new Observable(responseObserver =>{ // Here the XMLHttpRequest is create. });

}}

Response Classclass Response { ok: boolean; url: string; statusText: string; bytesLoaded: number; totalBytes: number; headers: Headers; private _body: string | Object;

constructor(responseOptions: ResponseOptions) { this._body = responseOptions.body; this.status = responseOptions.status; this.statusText = responseOptions.statusText; this.headers = responseOptions.headers; this.type = responseOptions.type; this.url = responseOptions.url; } ...}

Server Simulation To enable our server simulation, we replace the

XHRBackend service with the in-memory web api backend.

The in-memory api must to implements ConnectionBackend.

@NgModule({ providers :[ { provide: XHRBackend, useClass: InMemoryBackendService }, // in-mem server { provide: SEED_DATA, useClass: InMemoryDataService }, { provide: InMemoryBackendConfig, useValue: { delay: 600 } } ], imports :[HttpModule]})class AppModule{}

Thankseyalvardi.wordpress.com

Eyal Vardi

Site: http://ng-course.org

Blog: eyalVardi.wordpress.com

top related