JSONP_PROVIDERS

export JSONP_PROVIDERS : any[]

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

Provides a basic set of providers to use the Jsonp service in any application.

The JSONP_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 {NgFor} from 'angular2/common'; import {JSONP_PROVIDERS, Jsonp} from 'angular2/http'; @Component({ selector: 'app', providers: [JSONP_PROVIDERS], template: ` <div> <h1>People</h1> <ul> <li *ngFor="#person of people"> {{person.name}} </li> </ul> </div> `, directives: [NgFor] }) export class App { people: Array<Object>; constructor(jsonp:Jsonp) { jsonp.request('people.json').subscribe(res => { this.people = res.json(); }) } }

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

The providers included in JSONP_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 JSONP_PROVIDERS.

Example (live demo)

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

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

Example (live demo)

import {provide, Injector} from 'angular2/core';
import {JSONP_PROVIDERS, Jsonp, Response, JSONPBackend} from 'angular2/http';
import {MockBackend} from 'angular2/http/testing';

var people = [{name: 'Jeff'}, {name: 'Tobias'}];
var injector = Injector.resolveAndCreate([
  JSONP_PROVIDERS,
  MockBackend,
  provide(JSONPBackend, {useExisting: MockBackend})
]);
var jsonp = injector.get(Jsonp);
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);
    });
  });

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