2016-06-11 107 views
0

我得到JSON數據槽web服務承諾並獲得響應對象爲null進行。然後

myService.getData() 
      .then(function(data, status, headers, config){ 
      alert(data.length); 
    }... 

即使我能夠在then塊我得到的數據,並檢查槽瀏覽器控制檯內部代碼 沒有定義數據。

我在做什麼錯在這裏?

更新: 我的服務調用看起來像這樣

return $http.post("http:/...", { 
        headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==' } 
       }).success(function(data, status, headers, config){ 
        return data; 
       }).error(function(data, status, headers, config){ 
        alert('err'); 
       }); 
+0

你的服務代碼是什麼樣的?你是否還有承諾? – Seonixx

+0

您沒有從getData()返回承諾,因此您不能使用then方法。調整您的服務以返回HTTP承諾而不是數據。 – Seonixx

+0

你不能從'success'回調中'返回'。如果你想使用'.then'(儘管我沒有看到任何回調的理由) – Bergi

回答

0

要傳遞到決心的數據是一個對象,而不是一個數組。

對象沒有長度屬性,對象上的調用長度將使您未定義,除非您已爲其指定長度屬性。

var arrayLike = ['a', 'b'] 
console.log(arrayLike.length) 
//outputs: 2 

var objectLike = { "a": 1, "b": 2 } 
console.log(objectLike.length) 
// outputs: undefined (no length property on the object, only a and b. 
0

唯一想到的是'數據'對象是一個沒有長度的對象。如果它應該是字符串或數組,也許它是一個具有字符串或數組屬性的對象。調試時,請檢查您感興趣的數據在哪裏,並在使用length屬性之前獲取。

例如:

data.myProperty.length 
0

而是執行此操作:

myService.getData() 
     .success(function(data, status, headers, config){ 
       alert(data.length); 
      }).error(function(data, status, headers, config){ 
       alert('err'); 
      })... 

這是您的服務:

return $http.post("http:/...", { 
       headers: {'Authorization': 'Basic  QWxhZGRpbjpvcGVuIHNlc2FtZQ==' } 
      }); 

您需要返回由$ http.post的承諾()