Successfully reported this slideshow.

Http Communication in Angular 2.0

7

Share

Loading in …3
×
1 of 22
1 of 22

More Related Content

Related Books

Free with a 14 day trial from Scribd

See all

Related Audiobooks

Free with a 14 day trial from Scribd

See all

Http Communication in Angular 2.0

  1. 1. import { 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
  2. 2. // Add map operator import 'rxjs/add/operator/map'; // Add all operators to Observable import 'rxjs/Rx';
  3. 3. import {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; }); } } return observable Load Rx library
  4. 4. class MyOptions extends BaseRequestOptions { search: string = 'coreTeam=true'; } @NgModule({ ... provides:[{ provide : RequestOptions, useClass : MyOptions }] }) export class AppModule{}
  5. 5. 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); }
  6. 6. let 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(); });
  7. 7. @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]); } }
  8. 8. get( url : string, options?: RequestOptionsArgs): Observable<Response> { return httpRequest( this._backend, new Request(mergeOptions( this._defaultOptions, options, RequestMethod.Get, url))); }
  9. 9. 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; }
  10. 10. function 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; }
  11. 11. export class XHRBackend implements ConnectionBackend { constructor( private _browserXHR: BrowserXhr, private _baseResponseOptions: ResponseOptions) {} createConnection(request: Request): XHRConnection { return new XHRConnection( request, this._browserXHR, this._baseResponseOptions ); } }
  12. 12. export 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. }); } }
  13. 13. class 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; } ... }
  14. 14. @NgModule({ providers :[ { provide: XHRBackend, useClass: InMemoryBackendService }, // in-mem server { provide: SEED_DATA, useClass: InMemoryDataService }, { provide: InMemoryBackendConfig, useValue: { delay: 600 } } ], imports :[HttpModule] }) class AppModule{}

×