SlideShare une entreprise Scribd logo
1  sur  22
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
// Add map operator
import 'rxjs/add/operator/map';
// Add all operators to Observable
import 'rxjs/Rx';
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
class MyOptions extends BaseRequestOptions {
search: string = 'coreTeam=true';
}
@NgModule({
...
provides:[{
provide : RequestOptions,
useClass : MyOptions
}]
})
export class AppModule{}
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);
}
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();
});
@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]);
}
}
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;
}
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;
}
export class XHRBackend implements ConnectionBackend {
constructor( private _browserXHR: BrowserXhr,
private _baseResponseOptions: ResponseOptions) {}
createConnection(request: Request): XHRConnection {
return
new XHRConnection(
request,
this._browserXHR,
this._baseResponseOptions
);
}
}
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.
});
}
}
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;
}
...
}
@NgModule({
providers :[
{ provide: XHRBackend, useClass: InMemoryBackendService }, // in-mem server
{ provide: SEED_DATA, useClass: InMemoryDataService },
{ provide: InMemoryBackendConfig, useValue: { delay: 600 } }
],
imports :[HttpModule]
})
class AppModule{}
Http Communication in Angular 2.0

Contenu connexe

Tendances

Upgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.xUpgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.xEyal Vardi
 
Angular 2 Architecture
Angular 2 ArchitectureAngular 2 Architecture
Angular 2 ArchitectureEyal Vardi
 
Template syntax in Angular 2.0
Template syntax in Angular 2.0Template syntax in Angular 2.0
Template syntax in Angular 2.0Eyal Vardi
 
Performance Optimization In Angular 2
Performance Optimization In Angular 2Performance Optimization In Angular 2
Performance Optimization In Angular 2Eyal Vardi
 
Databinding and Performance-Tuning in Angular 2
Databinding and Performance-Tuning in Angular 2Databinding and Performance-Tuning in Angular 2
Databinding and Performance-Tuning in Angular 2Manfred Steyer
 
Angular 2.0 Routing and Navigation
Angular 2.0 Routing and NavigationAngular 2.0 Routing and Navigation
Angular 2.0 Routing and NavigationEyal Vardi
 
Angular 2.0 Pipes
Angular 2.0 PipesAngular 2.0 Pipes
Angular 2.0 PipesEyal Vardi
 
AngularJS Internal
AngularJS InternalAngularJS Internal
AngularJS InternalEyal Vardi
 
AngularJS $Provide Service
AngularJS $Provide ServiceAngularJS $Provide Service
AngularJS $Provide ServiceEyal Vardi
 
AngularJs $provide API internals & circular dependency problem.
AngularJs $provide API internals & circular dependency problem.AngularJs $provide API internals & circular dependency problem.
AngularJs $provide API internals & circular dependency problem.Yan Yankowski
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Eyal Vardi
 
AngularJS Compile Process
AngularJS Compile ProcessAngularJS Compile Process
AngularJS Compile ProcessEyal Vardi
 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IVisual Engineering
 
Angular 2.0 Views
Angular 2.0 ViewsAngular 2.0 Views
Angular 2.0 ViewsEyal Vardi
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptVisual Engineering
 
준비하세요 Angular js 2.0
준비하세요 Angular js 2.0준비하세요 Angular js 2.0
준비하세요 Angular js 2.0Jeado Ko
 
Angular server side rendering - Strategies & Technics
Angular server side rendering - Strategies & Technics Angular server side rendering - Strategies & Technics
Angular server side rendering - Strategies & Technics Eliran Eliassy
 
Workshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIWorkshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIVisual Engineering
 

Tendances (20)

Upgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.xUpgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.x
 
Angular 2 Architecture
Angular 2 ArchitectureAngular 2 Architecture
Angular 2 Architecture
 
Template syntax in Angular 2.0
Template syntax in Angular 2.0Template syntax in Angular 2.0
Template syntax in Angular 2.0
 
Performance Optimization In Angular 2
Performance Optimization In Angular 2Performance Optimization In Angular 2
Performance Optimization In Angular 2
 
Databinding and Performance-Tuning in Angular 2
Databinding and Performance-Tuning in Angular 2Databinding and Performance-Tuning in Angular 2
Databinding and Performance-Tuning in Angular 2
 
Angular 2.0 Routing and Navigation
Angular 2.0 Routing and NavigationAngular 2.0 Routing and Navigation
Angular 2.0 Routing and Navigation
 
Angular 2.0 Pipes
Angular 2.0 PipesAngular 2.0 Pipes
Angular 2.0 Pipes
 
AngularJS Internal
AngularJS InternalAngularJS Internal
AngularJS Internal
 
AngularJS $Provide Service
AngularJS $Provide ServiceAngularJS $Provide Service
AngularJS $Provide Service
 
AngularJs $provide API internals & circular dependency problem.
AngularJs $provide API internals & circular dependency problem.AngularJs $provide API internals & circular dependency problem.
AngularJs $provide API internals & circular dependency problem.
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
 
AngularJS Compile Process
AngularJS Compile ProcessAngularJS Compile Process
AngularJS Compile Process
 
Ngrx meta reducers
Ngrx meta reducersNgrx meta reducers
Ngrx meta reducers
 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte I
 
Angular 2.0 Views
Angular 2.0 ViewsAngular 2.0 Views
Angular 2.0 Views
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 
준비하세요 Angular js 2.0
준비하세요 Angular js 2.0준비하세요 Angular js 2.0
준비하세요 Angular js 2.0
 
Angular server side rendering - Strategies & Technics
Angular server side rendering - Strategies & Technics Angular server side rendering - Strategies & Technics
Angular server side rendering - Strategies & Technics
 
AngularJS Basics with Example
AngularJS Basics with ExampleAngularJS Basics with Example
AngularJS Basics with Example
 
Workshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIWorkshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte III
 

En vedette

Async & Parallel in JavaScript
Async & Parallel in JavaScriptAsync & Parallel in JavaScript
Async & Parallel in JavaScriptEyal Vardi
 
Node.js Socket.IO
Node.js  Socket.IONode.js  Socket.IO
Node.js Socket.IOEyal Vardi
 
Node.js File system & Streams
Node.js File system & StreamsNode.js File system & Streams
Node.js File system & StreamsEyal Vardi
 
Node js overview
Node js overviewNode js overview
Node js overviewEyal Vardi
 
Node.js Event Emitter
Node.js Event EmitterNode.js Event Emitter
Node.js Event EmitterEyal Vardi
 
Node.js Spplication Scaling
Node.js Spplication ScalingNode.js Spplication Scaling
Node.js Spplication ScalingEyal Vardi
 
AngulrJS Overview
AngulrJS OverviewAngulrJS Overview
AngulrJS OverviewEyal Vardi
 
AngularJS Routing
AngularJS RoutingAngularJS Routing
AngularJS RoutingEyal Vardi
 
Modules in ECMAScript 6.0
Modules in ECMAScript 6.0Modules in ECMAScript 6.0
Modules in ECMAScript 6.0Eyal Vardi
 
Making use of OpenStreetMap data with Python
Making use of OpenStreetMap data with PythonMaking use of OpenStreetMap data with Python
Making use of OpenStreetMap data with PythonAndrii Mishkovskyi
 
Rachel's grandmother's recipes
Rachel's grandmother's recipesRachel's grandmother's recipes
Rachel's grandmother's recipesEyal Vardi
 
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraAllen Wirfs-Brock
 

En vedette (14)

Async & Parallel in JavaScript
Async & Parallel in JavaScriptAsync & Parallel in JavaScript
Async & Parallel in JavaScript
 
Node.js Socket.IO
Node.js  Socket.IONode.js  Socket.IO
Node.js Socket.IO
 
Node.js File system & Streams
Node.js File system & StreamsNode.js File system & Streams
Node.js File system & Streams
 
Node js overview
Node js overviewNode js overview
Node js overview
 
Node.js Event Emitter
Node.js Event EmitterNode.js Event Emitter
Node.js Event Emitter
 
Nodejs
NodejsNodejs
Nodejs
 
Node.js Spplication Scaling
Node.js Spplication ScalingNode.js Spplication Scaling
Node.js Spplication Scaling
 
AngulrJS Overview
AngulrJS OverviewAngulrJS Overview
AngulrJS Overview
 
AngularJS Routing
AngularJS RoutingAngularJS Routing
AngularJS Routing
 
Modules in ECMAScript 6.0
Modules in ECMAScript 6.0Modules in ECMAScript 6.0
Modules in ECMAScript 6.0
 
Making use of OpenStreetMap data with Python
Making use of OpenStreetMap data with PythonMaking use of OpenStreetMap data with Python
Making use of OpenStreetMap data with Python
 
Rachel's grandmother's recipes
Rachel's grandmother's recipesRachel's grandmother's recipes
Rachel's grandmother's recipes
 
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
 
Angular 2 - Better or worse
Angular 2 - Better or worseAngular 2 - Better or worse
Angular 2 - Better or worse
 

Similaire à Http Communication in Angular 2.0

React Router: React Meetup XXL
React Router: React Meetup XXLReact Router: React Meetup XXL
React Router: React Meetup XXLRob Gietema
 
Protocol-Oriented Networking
Protocol-Oriented NetworkingProtocol-Oriented Networking
Protocol-Oriented NetworkingMostafa Amer
 
Higher Order Components and Render Props
Higher Order Components and Render PropsHigher Order Components and Render Props
Higher Order Components and Render PropsNitish Phanse
 
Spca2014 hillier build your_own_rest_service
Spca2014 hillier build your_own_rest_serviceSpca2014 hillier build your_own_rest_service
Spca2014 hillier build your_own_rest_serviceNCCOMMS
 
What's new in jQuery 1.5
What's new in jQuery 1.5What's new in jQuery 1.5
What's new in jQuery 1.5Martin Kleppe
 
Server Side Swift with Swag
Server Side Swift with SwagServer Side Swift with Swag
Server Side Swift with SwagJens Ravens
 
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0Frost
 
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017Codemotion
 
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsMashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsBastian Hofmann
 
Spring MVC Annotations
Spring MVC AnnotationsSpring MVC Annotations
Spring MVC AnnotationsJordan Silva
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
 
Creating an Uber Clone - Part XXIX - Transcript.pdf
Creating an Uber Clone - Part XXIX - Transcript.pdfCreating an Uber Clone - Part XXIX - Transcript.pdf
Creating an Uber Clone - Part XXIX - Transcript.pdfShaiAlmog1
 

Similaire à Http Communication in Angular 2.0 (20)

React Router: React Meetup XXL
React Router: React Meetup XXLReact Router: React Meetup XXL
React Router: React Meetup XXL
 
Protocol-Oriented Networking
Protocol-Oriented NetworkingProtocol-Oriented Networking
Protocol-Oriented Networking
 
Meteor iron:router
Meteor iron:routerMeteor iron:router
Meteor iron:router
 
What is your money doing?
What is your money doing?What is your money doing?
What is your money doing?
 
Higher Order Components and Render Props
Higher Order Components and Render PropsHigher Order Components and Render Props
Higher Order Components and Render Props
 
Reduxing like a pro
Reduxing like a proReduxing like a pro
Reduxing like a pro
 
Spca2014 hillier build your_own_rest_service
Spca2014 hillier build your_own_rest_serviceSpca2014 hillier build your_own_rest_service
Spca2014 hillier build your_own_rest_service
 
What's new in jQuery 1.5
What's new in jQuery 1.5What's new in jQuery 1.5
What's new in jQuery 1.5
 
Server Side Swift with Swag
Server Side Swift with SwagServer Side Swift with Swag
Server Side Swift with Swag
 
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Server Side Swift: Vapor
Server Side Swift: VaporServer Side Swift: Vapor
Server Side Swift: Vapor
 
Web api's
Web api'sWeb api's
Web api's
 
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
 
Mashing up JavaScript
Mashing up JavaScriptMashing up JavaScript
Mashing up JavaScript
 
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsMashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web Apps
 
Spring MVC Annotations
Spring MVC AnnotationsSpring MVC Annotations
Spring MVC Annotations
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
Creating an Uber Clone - Part XXIX - Transcript.pdf
Creating an Uber Clone - Part XXIX - Transcript.pdfCreating an Uber Clone - Part XXIX - Transcript.pdf
Creating an Uber Clone - Part XXIX - Transcript.pdf
 

Plus de Eyal Vardi

Smart Contract
Smart ContractSmart Contract
Smart ContractEyal Vardi
 
Proxies in ECMAScript 6.0
Proxies in ECMAScript 6.0Proxies in ECMAScript 6.0
Proxies in ECMAScript 6.0Eyal Vardi
 
Iterators & Generators in ECMAScript 6.0
Iterators & Generators in ECMAScript 6.0Iterators & Generators in ECMAScript 6.0
Iterators & Generators in ECMAScript 6.0Eyal Vardi
 
Symbols in ECMAScript 6.0
Symbols in ECMAScript 6.0Symbols in ECMAScript 6.0
Symbols in ECMAScript 6.0Eyal Vardi
 
Objects & Classes in ECMAScript 6.0
Objects & Classes in ECMAScript 6.0Objects & Classes in ECMAScript 6.0
Objects & Classes in ECMAScript 6.0Eyal Vardi
 
Scope & Functions in ECMAScript 6.0
Scope & Functions in ECMAScript 6.0Scope & Functions in ECMAScript 6.0
Scope & Functions in ECMAScript 6.0Eyal Vardi
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js ExpressEyal Vardi
 

Plus de Eyal Vardi (8)

Why magic
Why magicWhy magic
Why magic
 
Smart Contract
Smart ContractSmart Contract
Smart Contract
 
Proxies in ECMAScript 6.0
Proxies in ECMAScript 6.0Proxies in ECMAScript 6.0
Proxies in ECMAScript 6.0
 
Iterators & Generators in ECMAScript 6.0
Iterators & Generators in ECMAScript 6.0Iterators & Generators in ECMAScript 6.0
Iterators & Generators in ECMAScript 6.0
 
Symbols in ECMAScript 6.0
Symbols in ECMAScript 6.0Symbols in ECMAScript 6.0
Symbols in ECMAScript 6.0
 
Objects & Classes in ECMAScript 6.0
Objects & Classes in ECMAScript 6.0Objects & Classes in ECMAScript 6.0
Objects & Classes in ECMAScript 6.0
 
Scope & Functions in ECMAScript 6.0
Scope & Functions in ECMAScript 6.0Scope & Functions in ECMAScript 6.0
Scope & Functions in ECMAScript 6.0
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 

Dernier

Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...software pro Development
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 

Dernier (20)

Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 

Http Communication in Angular 2.0

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