使用 php API 从 angular6 中的 httpClient 响应中检索参数值?

Retrieving a parameter value from an httpClient response in angular6 with a php API?

我在 angular 中有一个方法 posts 值到 php api,当 http post 成功时,我得到一个 json 响应,但是当我尝试访问 res.status 或 json 对象中的任何参数时,我得到 Property 'status' does not exist on type 'Object'。如何获取响应对象中的参数值?

这是我的angularclass

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");
    }
  );
 }

这是我的 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.
?>

假设您为响应定义了一个接口:

interface Response {
  status: string;
}

将类型信息添加到您的 post 调用中:

this.http.post<Response>('http://myhost.com/phpapi/api.php',this.myData)

或任何,如果没有可用的类型定义

this.http.post<any>('http://myhost.com/phpapi/api.php',this.myData)