angular get请求
具体步骤:
1、在app.module.ts里引入HttpClientModule
,并注入
import { HttpClientModule } from '@angular/common/http';
imports: [
……
HttpClientModule
]
2、在用到的地方(组件)里引入HttpClient
,并在构造函数里声明
import {HttpClient} from "@angular/common/http";
constructor(public http:HttpClient) { }
3、get请求数据
// 简单使用
var api = "http://a.itying.com/api/productlist";
this.http.get(api).subscribe(response => { console.log(response); });
// 进一步扩展 apiUrl是http……,是从公共文件里引入的
// token 是已经定义好的,authorization是请求头字段,headers是请求头,params是请求参数
this.http.get<string>(apiUrl + '/ProjectInfo/GetProInfoSluiceSupplement',
{
headers: {
Authorization: 'Bearer ' + this.token,
},
params: {
Sorting: '0',
MaxResultCount: '1000',
}
}).subscribe( (res: any) => {
// 对获得的数据进行处理
console.log( res )
});
或者在commom.service.ts
服务文件里定义
// apiUrl是地址公共部分,params是传参对象
GetList(url: any, params: any) {
return this.http.get(apiUrl + url, {
headers: {
Authorization: this.token
},
params
}).toPromise();
}
或者不加.toPromise()
使用
// 引入common服务
// ChangeDetectorRef是处理angular脏数据加载的
// NzMessageService是ng-zorro组件之一
constructor(
private common: CommonService,
private ref: ChangeDetectorRef,
private message: NzMessageService,
) {
}
fun() {
const params: any = {
TableIGuid: this.id
};
this.personRoleList = [];
this.common.GetList('/proreport/ProreportStructtablePerson/GetAll', params).then((res: any) => {
if (res.code === 200) {
this.personRoleList = res.data.data;
this.ref.markForCheck()