javascript 角度替代 $http
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29361027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular alternative $http
提问by Eugene
In AngularJS for sending a request I use the builtin $http service.
在 AngularJS 发送请求时,我使用内置的 $http 服务。
What shall I use for sending a request to a server in Angular? I can't find any doc that covers the subject.
我应该使用什么来向 Angular 中的服务器发送请求?我找不到任何涵盖该主题的文档。
采纳答案by Charlie Martin
EDIT: There is an api previewfor the new http service on the Angular 2 websitenow
编辑:现在Angular 2网站上有新的 http 服务的api 预览
There is a basic http servicein Angular 2 currently, but its very minimalist right now. This software is in alpha and is very likely to change, so you may just want to use the fetch API, implement your own XMLHttpRequest, or use a library like jQueryinstead. Currently, the Angular 2 http api is essentially identical to the fetch API. Given that fetchis far less likely to change, I suggest just using that.
目前Angular 2 中有一个基本的http 服务,但它现在非常简约。该软件处于 alpha 阶段,很可能会发生变化,因此您可能只想使用fetch API,实现您自己的XMLHttpRequest,或者改用像jQuery这样的库。目前,Angular 2 http api 与fetch API基本相同。鉴于fetch不太可能改变,我建议只使用它。
If you want to use the Angular 2 service, hereis an example...
如果你想使用 Angular 2 服务,这里有一个例子......
import {bootstrap, Component, View, NgFor, Inject} from 'angular2/angular2';
import {Http, httpInjectables} from 'angular2/http';
@Component({selector: 'http-app'})
@View({
directives: [NgFor],
template: `
<h1>people</h1>
<ul class="people">
<li *ng-for="#person of people">
hello, {{person.name}}
</li>
</ul>
`
})
export class HttpCmp {
people: Object;
constructor(http: Http) {
http.get('./people.json').toRx().map(res => res.json()).subscribe(people => this.people = people);
}
}
回答by TGH
Simple http get sample:
简单的 http 获取示例:
http.get('./friends.json').map((res: Response) => res.json()).subscribe(res => this.result = res);
I have a working sample here: http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http
我在这里有一个工作示例:http: //www.syntaxsuccess.com/viewarticle/angular-2.0-and-http