繁体   English   中英

从离子中的 HTTP 请求中获取响应

[英]Get response from a HTTP request in ionic

如何在 ionic 中读取来自 http 请求的响应? 我正在 ionic 中创建一个登录页面,我试图从 json object 中的 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);

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

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

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

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

this.http.post("http://localhost:83/api/v2/signin.php", JSON.stringify(this.credentials), {观察: 'response').subscribe(fullResponse => {... ……

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM