1

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

1 Answer 1

1

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...

8
  • How i pass the parametres, for example 'id=1' Commented Mar 1, 2016 at 14:06
  • Using the URLSearchParams but it's not something specific to ES6... I updated my answer Commented Mar 1, 2016 at 14:14
  • Thanks for our help, I will tr and post the result Commented Mar 1, 2016 at 16:18
  • What is HTTP_PROVIDERS? Commented Mar 1, 2016 at 17:11
  • HTTP_PROVIDERS contains the list of providers to use HTTP. It contains the Http one but also others that the Http class relies on. You need to define them to be able to inject an Http instance in your services or components. Commented Mar 1, 2016 at 17:13

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.