简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM