[英]Retrieving a parameter value from an httpClient response in angular6 with a php API?
I have a method in angular that posts values to a php api, when http post is successful, I get a json response, but when I try to access res.status or any parameter in the json object I get Property 'status' does not exist on type 'Object'
. 我有一个角度的方法将值发布到php api,当http发布成功时,我得到一个json响应,但是当我尝试访问res.status或json对象中的任何参数时,我得到的
Property 'status' does not exist on type 'Object'
。 How can I get the value of a parameter in the response object? 如何获得响应对象中参数的值?
Here is my angular class 这是我的角度课
export class QuizComponent implements OnInit {
constructor(private http: HttpClient) { }
myData = { param1: 'This is param 1', param2: 'this is param 2' }
sendmydata(){
const req = this.http.post('http://myhost.com/phpapi/api.php',this.myData)
.subscribe(
res => {
console.log(res);
// how can I access res.status here?
res.status;//this line says Property 'status' does not exist on type 'Object'
},
err => {
console.log("Error occured");
}
);
}
and here is my PHP : (I know about prepared statements, just keeping it simple here): 这是我的PHP :(我知道准备好的语句,在这里保持简单):
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-
Allow-Headers, Authorization, X-Requested-With");
$db = "dbname";//Your database name
$dbu = "dbuser";//Your database username
$dbp = "dbpass";//Your database users' password
$host = "localhost";//MySQL server - usually localhost
$dblink = mysql_connect($host,$dbu,$dbp);
$seldb = mysql_select_db($db);
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$item1 = $request->param1;
$item2 = $request->param;
$sql = mysql_query("INSERT INTO `$db`.`table` (`id`,`item1`,`item2`)
VALUES ('','$item1','$item2');");
if($sql){
if (strcmp($item1, "") != 0) {
echo '{"status":"ok"}';
}
}else{
echo '{"status":"error"}';
}
mysql_close($dblink);//Close off the MySQL connection to save resources.
?>
Assuming you have an interface defined for your response: 假设您为响应定义了一个接口:
interface Response {
status: string;
}
Add the type information to your post
call: 将类型信息添加到您的
post
通话中:
this.http.post<Response>('http://myhost.com/phpapi/api.php',this.myData)
or any, if no type definition available 或任何(如果没有可用的类型定义)
this.http.post<any>('http://myhost.com/phpapi/api.php',this.myData)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.