【问题标题】:Retrieving a parameter value from an httpClient response in angular6 with a php API?使用php API从angular6中的httpClient响应中检索参数值?
【发布时间】:2018-06-24 20:36:15
【问题描述】:

我有一个 Angular 方法,可以将值发布到 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.
?>

【问题讨论】:

    标签: php json angular angular-httpclient


    【解决方案1】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-12
      • 1970-01-01
      • 1970-01-01
      • 2019-05-13
      • 2020-01-19
      • 1970-01-01
      相关资源
      最近更新 更多