小编典典
提供的很好的答案,但是我想补充一点,所以发布作为答案。
首先,要使用Rest API,我们需要导入Http和HTTP_PROVIDERS模块。当我们谈论Http时,第一步显然是。
但是,是的HTTP_PROVIDERS,在bootstrap文件中提供一个好习惯,因为通过这种方式,它是在全局级别提供的,并且可以像这样在整个项目中使用。
bootstrap(App, [
HTTP_PROVIDERS, some_more_dependencies
]);
和要包括的进口是…
import {Http, Response, RequestOptions, Headers, Request, RequestMethod} from 'angular2/http';
有时我们需要Headers在消耗API的同时提供发送access_token信息,并通过这种方式完成更多工作:
this.headers = new Headers();
this.headers.append("Content-Type", 'application/json');
this.headers.append("Authorization", 'Bearer ' + localStorage.getItem('id_token'))
现在到RequestMethods:基本上,我们使用GET,POST,但是您可以在此处引用更多选项…
我们可以使用requestmethods作为 RequestMethod.method_name
API还有更多选项,但现在我发布了一个POST请求示例,该示例将通过一些重要方法为您提供帮助:
PostRequest(url,data) {
this.headers = new Headers();
this.headers.append("Content-Type", 'application/json');
this.headers.append("Authorization", 'Bearer ' + localStorage.getItem('id_token'))
this.requestoptions = new RequestOptions({
method: RequestMethod.Post,
url: url,
headers: this.headers,
body: JSON.stringify(data)
})
return this.http.request(new Request(this.requestoptions))
.map((res: Response) => {
if (res) {
return [{ status: res.status, json: res.json() }]
}
});
}
您也可以在这里参考以获取更多信息。
也可以看看 -
在Angular 2中如何处理200以外的http状态代码。
更新资料
导入已从更改为
import {Http, Response, RequestOptions, Headers, Request, RequestMethod} from 'angular2/http';
至
import {Http, Response, RequestOptions, Headers, Request, RequestMethod} from '@angular/http';
2020-04-25