HTTP_PROVIDERS

export HTTP_PROVIDERS : any[]

exported from angular2/http defined in angular2/http.ts (line 154)

Provides a basic set of injectables to use the Http service in any application.

The HTTP_PROVIDERS should be included either in a component's injector, or in the root injector when bootstrapping an application.

Example (live demo)

import {Component} from 'angular2/core'; import {bootstrap} from 'angular2/platform/browser'; import {NgFor} from 'angular2/common'; import {HTTP_PROVIDERS, Http} from 'angular2/http'; @Component({ selector: 'app', providers: [HTTP_PROVIDERS], template: ` <div> <h1>People</h1> <ul> <li *ngFor="#person of people"> {{person.name}} </li> </ul> </div> `, directives: [NgFor] }) export class App { people: Object[]; constructor(http:Http) { http.get('people.json').subscribe(res => { this.people = res.json(); }); } active:boolean = false; toggleActiveState() { this.active = !this.active; } } bootstrap(App) .catch(err => console.error(err));

The primary public API included in HTTP_PROVIDERS is the Http class. However, other providers required by Http are included, which may be beneficial to override in certain cases.

The providers included in HTTP_PROVIDERS include:

There may be cases where it makes sense to extend the base request options, such as to add a search string to be appended to all URLs. To accomplish this, a new provider for RequestOptions should be added in the same injector as HTTP_PROVIDERS.

Example (live demo)

import {provide} from 'angular2/core'; import {bootstrap} from 'angular2/platform/browser'; import {HTTP_PROVIDERS, BaseRequestOptions, RequestOptions} from 'angular2/http'; class MyOptions extends BaseRequestOptions { search: string = 'coreTeam=true'; } bootstrap(App, [HTTP_PROVIDERS, provide(RequestOptions, {useClass: MyOptions})]) .catch(err => console.error(err));

Likewise, to use a mock backend for unit tests, the XHRBackend provider should be bound to MockBackend.

Example (live demo)

import {provide} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {HTTP_PROVIDERS, Http, Response, XHRBackend} from 'angular2/http';
import {MockBackend} from 'angular2/http/testing';

var people = [{name: 'Jeff'}, {name: 'Tobias'}];

var injector = Injector.resolveAndCreate([
  HTTP_PROVIDERS,
  MockBackend,
  provide(XHRBackend, {useExisting: MockBackend})
]);
var http = injector.get(Http);
var backend = injector.get(MockBackend);

// Listen for any new requests
backend.connections.observer({
  next: connection => {
    var response = new Response({body: people});
    setTimeout(() => {
      // Send a response to the request
      connection.mockRespond(response);
    });
  });

http.get('people.json').observer({
  next: res => {
    // Response came from mock backend
    console.log('first person', res.json()[0].name);
  }
});