我想在Angular2中使用http.post()向后端发送一个对象,并且我使用了以下代码。我无法将数据发送到后端。使用codeigniter框架进行服务器端编程。我不知道代码有什么问题。我应该对m component.ts做什么改变?
component.ts
let headers = new Headers();
headers.append('Content-Type', 'application/json; charset=UTF-8');
let addcategory_body={
'name':this.add_ser_name,
'description':this.add_ser_name,
'icon':'asfsdfdf.png'
}
this.http.post('http://www.viarchtechnologies.com/projects/coolmanz/index.php/ws/service', addcategory_body, {
headers: headers
}).subscribe(res => {
console.log('post result %o', res);
});
修改
ws.php
public function service() {
$this->load->model('Coolmodel','m',true);
$retval = array();
$icon = '';
if($_POST) {
$id = $this->input->post('id');
$name = $this->input->post('name');
$description = $this->input->post('description');
$active = $this->input->post('active');
$deleted = $this->input->post('deleted');
$display_order = $this->input->post('display_order');
$icon = $this->input->post('icon');
if($name == '') {
$retval['status'] = '0';
$retval['error'] = 'name missing';
} else if($description == '') {
$retval['status'] = '0';
$retval['error'] = 'description missing';
} else {
if($active == '') {
$active = 1;
}
if($deleted == '') {
$deleted = 0;
}
if($display_order == '') {
$display_order = $this->m->get_nextOrder_Service();
}
$data = array(
'name' => $name,
'active' => $active,
'icon' => $icon,
'description' => $description,
'deleted' => $deleted,
'display_order' => $display_order
);
$retval['status'] = '1';
if($id == '') {
$this->m->saveToDB('services', $data);
} else {
$data['modified'] = date('Y-m-d H:i:s');
$this->m->updateDB('services', $data, 'id', $id);
}
//$user=$this->m->login($userlogin, md5($password));
}
} else {
$services = $this->m->get_services();
$retServices = array();
$i = 0;
foreach($services as $service) {
if($service['icon'] != '') {
$service['icon'] = base_url().'images/'.$service['icon'];
}
$retServices[$i++] = $service;
}
$retval['status'] = '1';
$retval['services'] = $retServices;
}
header('Content-Type: application/json');
echo json_encode($retval, JSON_UNESCAPED_UNICODE);
}
[![Respose][1]][1]
答案 0 :(得分:0)
问题是当您发送$_POST
正文是http post body
对象时,您期望来自json
变量的值。您的功能服务现在不会。
尝试:替换您检查if
数据的POST
语句:
if($this->input->method() === 'post') {
$obj = json_decode($this->input->raw_input_stream);
$id = $obj->id;
$name = $obj->name;
$description = $obj->description;
$active = $obj->active;
$deleted = $obj->deleted;
$display_order = $obj->display_order;
$icon = $obj->icon;
}