Http Communication in Angular 2.0
-
Upload
eyal-vardi -
Category
Software
-
view
1.980 -
download
1
Transcript of Http Communication in Angular 2.0
![Page 1: Http Communication in Angular 2.0](https://reader035.fdocuments.net/reader035/viewer/2022062904/5872a1971a28ab07208b5dbd/html5/thumbnails/1.jpg)
Angular 2HTTP Communication
Eyal Vardi
Site: http://ng-course.org
Blog: eyalVardi.wordpress.com
![Page 2: Http Communication in Angular 2.0](https://reader035.fdocuments.net/reader035/viewer/2022062904/5872a1971a28ab07208b5dbd/html5/thumbnails/2.jpg)
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](https://reader035.fdocuments.net/reader035/viewer/2022062904/5872a1971a28ab07208b5dbd/html5/thumbnails/3.jpg)
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](https://reader035.fdocuments.net/reader035/viewer/2022062904/5872a1971a28ab07208b5dbd/html5/thumbnails/4.jpg)
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](https://reader035.fdocuments.net/reader035/viewer/2022062904/5872a1971a28ab07208b5dbd/html5/thumbnails/5.jpg)
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](https://reader035.fdocuments.net/reader035/viewer/2022062904/5872a1971a28ab07208b5dbd/html5/thumbnails/6.jpg)
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](https://reader035.fdocuments.net/reader035/viewer/2022062904/5872a1971a28ab07208b5dbd/html5/thumbnails/7.jpg)
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](https://reader035.fdocuments.net/reader035/viewer/2022062904/5872a1971a28ab07208b5dbd/html5/thumbnails/8.jpg)
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](https://reader035.fdocuments.net/reader035/viewer/2022062904/5872a1971a28ab07208b5dbd/html5/thumbnails/9.jpg)
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](https://reader035.fdocuments.net/reader035/viewer/2022062904/5872a1971a28ab07208b5dbd/html5/thumbnails/10.jpg)
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](https://reader035.fdocuments.net/reader035/viewer/2022062904/5872a1971a28ab07208b5dbd/html5/thumbnails/11.jpg)
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](https://reader035.fdocuments.net/reader035/viewer/2022062904/5872a1971a28ab07208b5dbd/html5/thumbnails/12.jpg)
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](https://reader035.fdocuments.net/reader035/viewer/2022062904/5872a1971a28ab07208b5dbd/html5/thumbnails/13.jpg)
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](https://reader035.fdocuments.net/reader035/viewer/2022062904/5872a1971a28ab07208b5dbd/html5/thumbnails/14.jpg)
HTTP Internal
![Page 15: Http Communication in Angular 2.0](https://reader035.fdocuments.net/reader035/viewer/2022062904/5872a1971a28ab07208b5dbd/html5/thumbnails/15.jpg)
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](https://reader035.fdocuments.net/reader035/viewer/2022062904/5872a1971a28ab07208b5dbd/html5/thumbnails/16.jpg)
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](https://reader035.fdocuments.net/reader035/viewer/2022062904/5872a1971a28ab07208b5dbd/html5/thumbnails/17.jpg)
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](https://reader035.fdocuments.net/reader035/viewer/2022062904/5872a1971a28ab07208b5dbd/html5/thumbnails/18.jpg)
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](https://reader035.fdocuments.net/reader035/viewer/2022062904/5872a1971a28ab07208b5dbd/html5/thumbnails/19.jpg)
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](https://reader035.fdocuments.net/reader035/viewer/2022062904/5872a1971a28ab07208b5dbd/html5/thumbnails/20.jpg)
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](https://reader035.fdocuments.net/reader035/viewer/2022062904/5872a1971a28ab07208b5dbd/html5/thumbnails/21.jpg)
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](https://reader035.fdocuments.net/reader035/viewer/2022062904/5872a1971a28ab07208b5dbd/html5/thumbnails/22.jpg)
Thankseyalvardi.wordpress.com
Eyal Vardi
Site: http://ng-course.org
Blog: eyalVardi.wordpress.com