2015-04-02 32 views
0

JSON以只讀屬性:無法分配,同時對陣列增加新的項目裏面transformResponse

[{"name":"John"},{"name":"Jim"}] 

錯誤:

Cannot assign to read only property 'age' of [ at transformResponse (angular.js?compile=false:9224) at processQueue (angular.js?compile=false:12914) 

的Javascript:

angular.module('myservice', []) 
    .factory("demoService", function ($http,rootUrl) { 
      return { 
       getDashboardData: function() { 
        return $http({ 
         url: rootUrl + '/api/mainpage', 
         method: 'GET', 
         transformResponse: function (data) { 
          var currentDate = new Date(); 

          for (var i = 0; i < data.length; i++) { 
           var row = data[i]; 
           row["age"] = 35; 
          } 
          return data; 
         } 
       }); 
      } 
     } 
}); 
+0

我在代碼中看不到任何問題,但是,您可以在'transformResponse'中爲'data'做一個'console.log'並檢查? – 2015-04-02 06:37:01

回答

0

的數據需要被反序列化然後才能操縱它。當你指定一個額外的transformResponse時,傳遞給它的數據對象還沒有通過Angular的默認transformResponse,所以它尚未被解析爲JSON。我通常將JSON解析爲transformResponse中的第一步,如下所示:data = JSON.parse(data);

angular.module('myservice', []) 
.factory("demoService", function ($http,rootUrl) { 
     return { 
      getDashboardData: function() { 
       return $http({ 
        url: rootUrl + '/api/mainpage', 
        method: 'GET', 
        transformResponse: function (data) { 
         // parse data as JSON first 
         data = JSON.parse(data); 
         var currentDate = new Date(); 

         for (var i = 0; i < data.length; i++) { 
          var row = data[i]; 
          row["age"] = 35; 
         } 
         return data; 
        } 
      }); 
     } 
    } 

});

+0

謝謝Shelly .. data = JSON.parse(data);做了魔術.. – Hakucha 2015-04-07 05:42:57