2017-07-17 34 views
0

我有一個服務返回這個簡單的JSON:爲什麼AngularJS json數據嵌套?

{ 
    "successYN": true, 
    "msg": "Success!", 
    "errors": null 
} 

我有這樣的控制器:

app.controller('formController', function ($http, $httpParamSerializerJQLike) { 
var frmVM = this 
frmVM.formData = {} 

frmVM.frmSubmit = function() { 
    console.log('form was submitted with: ' + frmVM.formData.name + ' ' + frmVM.formData.superheroAlias) 

    // post the data to the back end 
    $http({ 
      method: 'POST', 
      url: '/contact-post', 
      data: $httpParamSerializerJQLike(frmVM.formData), // pass in data as strings 
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload) 
     }) 
     .then(function (data) { 

      console.log(data); 

      var innerData = data.data; 

      console.log(innerData) 
      console.log(innerData.errors) 
      console.log(innerData.successYN) 

      if (!innerData.successYN) { 
       console.log("Not successful!") 
       // if not successful, bind errors to error variables 
       frmVM.errorName = innerData.errors.name; 
       frmVM.errorSuperhero = innerData.errors.superheroAlias; 
      } else { 
       // if successful, bind success message to message 
       frmVM.message = innerData.msg; 
      } 
     }); 
    }; 
}) 

我在我的形式controller as語法和一切工作正常。但是,我看到在 數據對象是這樣的:

enter image description here

因此,該數據具有這樣的被訪問:

var innerData = data.data; 

之前,我可以訪問數據:

​​

任何人都可以解釋爲什麼發生這種情況和/或我做錯了什麼?

+0

你沒有做錯什麼。這是來自AngularJS中http請求生成器的響應。它添加了一些響應標題,關於請求的信息以及從服務器檢索到的「數據」。它將數據存儲在一個'data'對象中,您可以從json文件 – Jer

+0

中訪問JSON對象鍵謝謝,您應該將此作爲答案,因爲它可以最好地解釋發生的事情。 –

回答

1

參數「data」基本上是響應對象,它包含響應頭以及響應的主體。 ForExample: 如果您需要的參數響應,那麼得到的響應數據,你將不得不調用

var data = response.data

,如果你想從響應頭,你必須做以下幾點:

var authorization = response.headers('Authorization'); 

在。然後功能,您將不得不通過2個處理器1的成功響應(200 OK)和第2的失敗響應(400錯誤的請求)

所以

.then(function(response) { 
// here you extract data from response. like response.data 
}, function(errorResponse) { 
// handle error here like errorResponse.status 
}); 
+0

感謝您的迴應。但我已經看到代碼做這樣的東西'.success(函數(數據){如果(!data.success){'。爲什麼我不得不做'data.data.success'? –

+0

兄弟請參閱更新。如果您有任何問題,請告訴我們 –

+0

.success的用法不建議使用,請參閱以下鏈接 http://www.codelord.net/2015/05/25/dont-use-%24https-success/ –

1

$http將僅返回以下格式的數據,因爲這是它的定義方式。

來自服務器的響應是具有這些屬性的對象:的.config用於生成請求對象

1)。

2).data一個字符串或一個對象,攜帶來自 服務器的響應。

3).headers函數用於獲取標題信息。

4).status一個定義HTTP狀態的數字。

5).statusText定義HTTP狀態的字符串。