http communication in angular 2.0

22
Angular 2 HTTP Communication Eyal Vard Site: http://ng-course.o Blog: eyalVardi.wordpress.

Upload: eyal-vardi

Post on 16-Apr-2017

1.978 views

Category:

Software


1 download

TRANSCRIPT

Page 1: Http Communication in Angular 2.0

Angular 2HTTP Communication

Eyal Vardi

Site: http://ng-course.org

Blog: eyalVardi.wordpress.com

Page 2: Http Communication in Angular 2.0

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

Page 3: Http Communication in Angular 2.0

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

Page 4: Http Communication in Angular 2.0

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

Page 5: Http Communication in Angular 2.0

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';

Page 6: Http Communication in Angular 2.0

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.

Page 7: Http Communication in Angular 2.0

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

Page 8: Http Communication in Angular 2.0

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)

Page 9: Http Communication in Angular 2.0

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{}

Page 10: Http Communication in Angular 2.0

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);}

Page 11: Http Communication in Angular 2.0

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();

});

Page 12: Http Communication in Angular 2.0

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.

Page 13: Http Communication in Angular 2.0

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]); }}

Page 14: Http Communication in Angular 2.0

HTTP Internal

Page 15: Http Communication in Angular 2.0

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))); }

Page 16: Http Communication in Angular 2.0

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;}

Page 17: Http Communication in Angular 2.0

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;

}

Page 18: Http Communication in Angular 2.0

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 ); }}

Page 19: Http Communication in Angular 2.0

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. });

}}

Page 20: Http Communication in Angular 2.0

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; } ...}

Page 21: Http Communication in Angular 2.0

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{}

Page 22: Http Communication in Angular 2.0

Thankseyalvardi.wordpress.com

Eyal Vardi

Site: http://ng-course.org

Blog: eyalVardi.wordpress.com