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'
. 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
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:
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)