簡體   English   中英

使用php API從angular6的httpClient響應中檢索參數值?

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

我有一個角度的方法將值發布到php api,當http發布成功時,我得到一個json響應,但是當我嘗試訪問res.status或json對象中的任何參數時,我得到的Property 'status' does not exist on type 'Object' 如何獲得響應對象中參數的值?

這是我的角度課

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM