Fabio Santos
Fabio Santos

Reputation: 253

HTTP GET request with AngularJS 2 and ES6

How can I do HTTP GET request in AngularJS 2 with JavaScript (ES6)? The documentation only shows with TypeScript.

Upvotes: 1

Views: 538

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202326

You could use something like that:

import {Http, URLSearchParams} from 'angular2/http';

@Injectable()
export class SomeHttpService {
  constructor(http) {
    this.http = http;
  }

  getSomething() {
    URLSearchParams params = new URLSearchParams();
    params.set('id', '1');
    return this.http.get('http://...', { search: params }).map(res => res.map());

    /*
      or if you need to subscribe in the service

      this.http.get('http://...').map(res => res.map())
               .subscribe(
                 (data) => {
                   // do something with data
                 }
               );
    */
  }

  static get parameters() {
    return [[Http]];
  }
}

Don't forget to import the Angular2 Http module file:

<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>
<script src="node_modules/angular2/bundles/http.dev.js"></script> <---

and to set the HTTP_PROVIDERS providers when bootstrapping your application:

import {HTTP_PROVIDERS} from 'angular2/http';
(...)

bootstrap(AppComponent, [ HTTP_PROVIDERS ]);

In fact, the only thing that is specific to ES6 is the way to configure dependency injection with the static getter...

Upvotes: 1

Related Questions