如何在 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\":\"[email protected]\"}}", 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 回答

江戶川亂折騰
TA貢獻1851條經驗 獲得超5個贊
string
您將從后端獲取響應正文。您必須將正文解析為 JSON,然后使用它。
只需將行從 更改為this.data = data;
即可this.data = JSON.parse(data)
。
或者this.data = JSON.parse(data._data);

縹緲止盈
TA貢獻2041條經驗 獲得超4個贊
告訴 HttpClient 您希望使用 post() 方法的觀察選項獲得完整響應:
this.http.post("http://localhost:83/api/v2/signin.php", JSON.stringify(this.credentials), {observe: 'response') .subscribe(fullResponse => { ... ....
現在,httpClient 返回 HttpResponse 類型的 Observable,而不僅僅是正文中包含的 JSON 數據。
- 2 回答
- 0 關注
- 162 瀏覽
添加回答
舉報
0/150
提交
取消