2016-09-23 21 views
0

我正在使用angular的$資源從API獲取數據。我的角$資源配置如下:Angular.isArray(data)爲數組返回false

Priorities : $resource (baseUrl + 'priorities/:priorityType/:uuid/all', {}, { 
    query : { 
     method: 'GET', 
     params: { 
      priorityType : '@priorityType', 
      uuid : '@uuid' 
     }, 
     isArray: true 
    } 
}) 

但是,調用Priorities.query一個$資源時:badcfg引發錯誤:「預期的響應,以包含數組,但得到了一個對象」。此異常意味着該API返回的對象,但$資源被配置爲接收陣列 - 但API顯然是返回一個數組:

[{"priority":"ONE","count":5,"globalCount":3037}] 

挖成角resource.js,異常被拋出在這裏:

if (angular.isArray(data) !== (!!action.isArray)) { 
    throw $resourceMinErr('badcfg', ...); 
} 

預期!!action.isArray返回true,但奇怪的是angular.isArray(data)返回false。這裏發生了什麼?

+0

'但是API顯然是返回一個數組:'等待,是你得到的_JSON_嗎?如果是這樣,你需要先解析它。 – vlaz

+0

@vlaz在調用任何transformResponse方法之前,會引發此異常。 – cscan

回答

0

響應需要從json轉換而來。

Mixin.staticMethod(Type, null, 'apiResponseTransformer', function (json) { 
    var data = angular.fromJson(json); 
    if (angular.isArray(data)) { 
     return data.map(Type.build).filter(Boolean); 
    } 
    return Type.build(data); 
})