从Ionic的HTTP请求获取响应

时间:2020-06-27 01:01:14

标签: php ionic-framework ionic3

如何读取来自ionic的http请求的响应?我正在用ionic创建一个登录页面,并且试图从json对象中的php代码获取响应。来自后端的响应是我无法用离子捕捉到的。

.ts代码

this.http.post("http://localhost:83/api/v2/signin.php", JSON.stringify(this.credentials))
        .subscribe(data => {
          
          this.data = data;
          console.log(this.data);

          if(data.response=="success"){
            let toast = this.toastCtrl.create({
              message: 'Login was successfully',
              duration: 3000,
              position: 'top',
              cssClass: 'dark-trans',
              closeButtonText: 'OK',
              showCloseButton: true
            });
            toast.present();
           
            this.navCtrl.setRoot(HomePage);           
            this.storage.set("session",response);
            this.global.session=response;
          }else{
            this.global.loginState="login";
            let alert = this.alertCtrl.create({
              
              subTitle: data.response,
              buttons: ['OK']
            });
            alert.present();
          } 

登录失败时,控制台中将显示以下内容

Response {_body: "{"response":"Invalid login details entered"}"

成功,我有

 Object { _body: "{\"response\":\"success\",
   \"data\":{\"id\":\"4\",\"name\":\"Eli James\",
   \"email\":\"eli_james@gmail.com\"}}",
  status: 200, ok: true, statusText: "OK",

我的php代码是这样的:

         if($row['email']==$email AND 
                 $row['status']=='1'){
       
                       $response=array(
                        "response"=>"success",
                        "data"=>array(
                            "id"=>$row['id'],
                            "name"=>$row['name'],                     
                            "email"=>$row['email']

                            )

                        );          
                      }else{
                    $response=array("response"=>"Invalid login details entered");
                     }
                   echo json_encode($response);

2 个答案:

答案 0 :(得分:1)

您将从后端获得string作为响应正文。您将必须将正文解析为JSON,然后使用它。

只需将行从this.data = data;更改为this.data = JSON.parse(data)

this.data = JSON.parse(data._data);

答案 1 :(得分:0)

使用post()方法的watch选项告诉HttpClient您想要完整的响应:

this.http.post(“ http:// localhost:83 / api / v2 / signin.php”,JSON.stringify(this.credentials),{观察:“响应”) .subscribe(fullResponse => { .......

现在,httpClient返回的是HttpResponse类型的Observable,而不仅仅是正文中包含的JSON数据。