如何使用JavaScript(ES6)在AngularJS 2中执行HTTP GET请求?该文档仅显示TypeScript。
答案 0 :(得分:1)
你可以使用类似的东西:
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]];
}
}
不要忘记导入Angular2 Http模块文件:
<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> <---
并在引导您的应用程序时设置HTTP_PROVIDERS
提供程序:
import {HTTP_PROVIDERS} from 'angular2/http';
(...)
bootstrap(AppComponent, [ HTTP_PROVIDERS ]);
事实上,ES6唯一特有的是使用静态getter配置依赖注入的方法......