簡體   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