【发布时间】:2018-09-10 07:27:22
【问题描述】:
我需要使用Angular 6 的HttpClient 将一组数据发送到PHP 服务器。
我有一些下拉列表,我从中选择并推入一个数组:
arrayOfLegalProtection=[];
addSit(){
let l_id = '';
let p_id = '';
let s_id = '';
let add_date = '';
l_id = this.formGroup.controls['l_id'].value;
p_id = this.formGroup.controls['p_id'].value;
s_id = this.formGroup.controls['s_id'].value;
add_date = this.formGroup.controls['add_date'].value;
this.showSubHeader++;
this.arrayOfLegalProtection.push({lId: l_id,
pId: p_id,
sId: s_id,
addDate: add_date})
console.log(this.arrayOfLegalProtection);
}
控制台结果显示正确的推送值:
[{"lId":"1","prId":"1","sId":"2","addDate":"2018-09-14"},
{"lId":"","pId":"1","sId":"5","addDate":"2018-09-14"},
{"lId":"","pId":"2","sId":"","addDate":"2018-09-20"}]
现在,我需要将此数组添加到 httpclient post 方法并将其发送到服务器,但正如讨论中所说的 of this post,数组无法通过 angular 的 HttpClient 库发送。
我们需要使用append,或者JSON.stringify()或者.append()。
我posted a question 使用JSON.stringify() 的方法后,你可以看到有错误。即使多维数组包含 0 或 N 行数据,即使 echo count($array) 始终是 1。
所以我换了另一种方法,使用.append():
saveUnitData(unit_type,
location_type_id, user_id, number_of_hh, unit_status, add_date, arrayOfActualities)
{
console.log(user_id);
let httpParam = new HttpParams().set('unit_type', unit_type)
.set('location_type_id', location_type_id)
.set('user_id', user_id)
.set('number_of_hh', number_of_hh)
.set('unit_status',unit_status)
.set('add_date', add_date);
Object.keys(arrayOfActualities).forEach(key=>{
httpParam = httpParam.append('arrayOfActualities', arrayOfActualities);
})
//.set('arrayOfActualities', arrayOfActualities);
let headerOptions = new HttpHeaders();
headerOptions.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
console.log('h'+arrayOfActualities);
return this.http.post(this.globalVar.UnitSavedataUrl, httpParam, {headers: headerOptions});
}
使用此代码:
Object.keys(arrayOfActualities).forEach(key=>{
httpParam = httpParam.append('arrayOfActualities', arrayOfActualities);
我尝试使用 append 将对象转换为数组,以便可以通过 httpClient 服务发送。
在请求的头部,我们可以看到发送的普通数据,但是数组却被重复了上百次。
服务器的响应总是:
C:\wamp64\www\dev\UnitSaveData.php:23:string '[{"legalId":"","protectionId":"","situationId":"","addDate":"2018-09-14"},{"legalId":"","protectionId":" ","situationId":"","addDate":"2018-09-14"}]' (长度=147)
但没有向数据库中添加任何内容。
请注意PHP脚本与previous unanswered post相同
【问题讨论】:
-
我曾经遇到过使用
HttpClient将数组发送到 API 的问题。发布请求有一个body,您几乎可以在其中发送任何 js 对象。 Http 参数是附加到您的 url 的参数:如果您使用 post 请求,则不需要它。 -
顺便说一句
HttpHeaders是不可变的,所以你需要这样做:let headerOptions = new HttpHeaders().append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); -
@trichetriche 请检查我帖子中添加的 github 链接,并阅读有关使用 httpClients 发送数组的问题。如果你是对的,我在构建数组时遇到了问题,所以我添加了推入数组的方法。
-
@droidnation 如前所述,there is no issue with sending arrays through post。如果您有问题,请提供minimal reproducible example 复制它。
-
您的 PHP 脚本正在调用
json_encode(),它会生成一个 JSON 字符串。如果您的意图是将 JSON 转换为数组,请执行json_decode()。不过,在任何事情之前,请确保您传递给json_decode()的任何内容都不是数组。
标签: php json angular httpclient angular6