How can I do HTTP GET request in AngularJS 2 with JavaScript (ES6)? The documentation only shows with TypeScript.
1 Answer
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...
-
-
Using the
URLSearchParams
but it's not something specific to ES6... I updated my answer Commented Mar 1, 2016 at 14:14 -
-
-
HTTP_PROVIDERS
contains the list of providers to use HTTP. It contains theHttp
one but also others that theHttp
class relies on. You need to define them to be able to inject anHttp
instance in your services or components. Commented Mar 1, 2016 at 17:13