$ resource:包含一个对象但得到一个数组的预期响应

时间:2015-06-05 07:43:07

标签: javascript json angularjs

我知道这个问题已经存在于SO(就像这里:Error in resource configuration. Expected response to contain an object but got an array),即使我几天前已经遇到过这个错误,我也没有找到我为什么会这样做的原因。我现在得到它。

一方面,我在Node Express中有一个RESTful API。它让我可以访问数据库,我试图获取一些数据。使用特定$resource请求时,我获得此JSON(使用Postman测试):

 [
   {
    "ref": 2,
    "type": "string here",
    "matriculeMD": 4567,
    "name": "William",
    "date": "2016-09-14T22:00:00.000Z",
    "client": 1
   },
   {
    "ref": 4,
    "type": "string here",
    "matriculeMD": 1589,
    "name": "Averell",
    "date": "0000-00-00",
    "client": 1
   }
 ]

另一方面,我有一个Angular JS应用程序。这个使用工厂从API获取数据:

 .factory('Things', ['$resource', function($resource) {

    return $resource(

        'api_url/:client_id',
        {client_id: '@client_id'}, // getting some data from an ID
        {'query' : {
                        method : 'GET', // ofc, it's a get request in the API
                        isArray : false // to be sure to get an object and not an array
                    }
        } 

我还有一个使用这个工厂的控制器,试图用param执行查询:

 app.controller('ctrl', ['$scope','Things', function ($scope,$things) 

    {
      $scope.thing = $things.query({},{'client_id':'1'}); 
      // replacing '@client_id' from factory with 1. I also tried with quoteless 1.
    }
 ]);

最后,我有一个html视图,我尝试使用我应该使用$scope.thing进入<div ng-repeat'thing in things'>{{thing.ref}}</div>的数据。

通过阅读其他帖子,我确信向工厂添加isArray : false可以解决问题,因为它已经在另一家工厂修复了它。

有什么想法吗?

修改:感谢您的回复。我改变了我的工厂代码:

.factory('Things', ['$resource', function($resource) {

        return $resource(

            'api_url/:client_id',
            {client_id: '@client_id'}, // getting some data from an ID
            {'query' : {
                            method : 'GET', // ofc, it's a get request in the API
                            isArray : true //
                        }
            } 

它修正了错误。现在,我处理了我的$scope内容的另一个问题,该内容未定义并发送$promise : Promise, $resolved : Resolved。我阅读了$resource doc以了解它的含义,但我仍然不知道如何使它工作。

4 个答案:

答案 0 :(得分:0)

正如doldt之前所说,你实际上是在期待一个数组。

您的回复是一系列对象。

您可以将isArray更改为true,或者更改服务器上的响应以返回对象。

更改后,您可以通过这种方式在控制器上使用您的资源(为$资源提供回调,因为您现在处理的是promises):

$things.query( {}, { 'client_id' : '1' }, function( response ){
    $scope.thing = response;
}); 

答案 1 :(得分:0)

我认为您使用 isArray 标记做错了。如果您要发送数组,则必须 true

试试吧......

答案 2 :(得分:0)

&#13;
&#13;
// Code goes here

var myApp = angular.module('myApp', ['ngResource']);

myApp.factory('Things', ['$resource',
  function($resource) {

    return $resource(

      'data/sample.json'
      //, {
      //  client_id: '@client_id'
      //}, // getting some data from an ID
      //{
      //  'query': {
      //    method: 'GET', // ofc, it's a get request in the API
      //    isArray: true // to be sure to get an object and not an array
      //  }
      //})
    )
  }
]);

myApp.controller('myCtrl', function($scope, Things) {

  Things.query({}, {
    'client_id': '1'
  }).$promise.then(function(data) {
    $scope.thing = data;
    console.log($scope.thing);
  })
});
&#13;
[
   {
    "ref": 2,
    "type": "string here",
    "matriculeMD": 4567,
    "name": "William",
    "date": "2016-09-14T22:00:00.000Z",
    "client": 1
   },
   {
    "ref": 4,
    "type": "string here",
    "matriculeMD": 1589,
    "name": "Averell",
    "date": "0000-00-00",
    "client": 1
   }
 ]
&#13;
<!DOCTYPE html>
<html ng-app="myApp">

<head>
  <script data-require="angular.js@*" data-semver="2.0.0-alpha.26" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular-resource.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-controller="myCtrl">
  <h1>{{1/2}}</h1>
  <ul ng-repeat="t in thing">
    <li>{{t.name}}</li>
  </ul>
</body>

</html>
&#13;
&#13;
&#13;

- 输出 0.5

威廉 埃夫里尔

答案 3 :(得分:0)

尝试:

ALTER function [eo].[forecast_baseline] (@monthkey as char(6)) 
  returns @results table(
  [billing_date] date,
  [year] int,
  [type] varchar(max),
  [dollars] float,
  [units] float,
  [CC] int,
  [offering] varchar(max),
  [IntegratedReleasePlanNm] varchar(max),
  [ProjectId] varchar(max),
  [ProjectNm]  varchar(max),
  [ModelEstimateId] varchar(max),
  [query] varchar(max),
  [ItemGroupId]  varchar(max),
  CashflowType varchar(12),
  plotdate datetime
  )
  as
  begin
    declare @StartTime datetime = (SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(getdate())-1),getdate()),101))
    declare @EndTime datetime = DATEADD(year, +5, @StartTime)
    declare @Interval int = 1;

    WITH yearsinmonths (
      [datetimemonth], 
      [enddatetimemonth]) AS ( 
          SELECT
            @StartTime datetimemonth, 
            DATEADD(month, @Interval, @StartTime) AS enddatetimemonth
          UNION ALL
          SELECT
            EndRange, 
            DATEADD(month, @Interval, enddatetimemonth)
          FROM 
            cSequence 
          WHERE 
            DATEADD(month, @Interval, enddatetimemonth) < @EndTime
    ), 

    forecast_baseline (
      [billing_date],
      [year],
      [type],
      [dollars],
      [units],
      [CC],
      [offering],
      [IntegratedReleasePlanNm],
      [ProjectId],
      [ProjectNm],
      [ModelEstimateId],
      [query],
      [ItemGroupId],
      [CashflowType]) as (
          select 
            dateadd(month,-1,convert(date, a.CHARGE_MONTH+'01', 112))
            ,year(dateadd(month,-1,convert(date, a.CHARGE_MONTH+'01', 112)))
            ,'Baseline'
            ,sum(cast(a.CHARGE_AMOUNT as money))
            ,sum(cast (PPGUNITS as float))
            ,ORG_CC
            ,[offering]
            ,'Baseline'
            ,'baseline'
            ,'baseline'
            ,'baseline'
            ,'baseline'
            ,'N/A'
            ,'N/A'
          from 
            [sources].[feeds].[MARS2IEO_MARS_BD12_INV_LOB_EXTRACTS] a join sources.[md].[MARS_ITEMID_MAPPING] b 
              on a.offering=b.itemid 
          where 
            host_name is not null 
            and (a.org_sort_code like ('KBBFA%') or 
                a.org_sort_code like ('KBBFB%') or
                a.org_sort_code like ('KBBDD%'))
            and b.category in ('server','disk','tape')
            and cast(year(dateadd(month,-1,convert(date,     a.CHARGE_MONTH+'01', 112))) as char(4)) + RIGHT('00' + CONVERT(VARCHAR,month(dateadd(month,-1,convert(date, a.CHARGE_MONTH+'01', 112)))), 2) <= @monthkey -- this is the line that throws the error
          group by 
            offering
            ,ORG_CC
            ,dateadd(month,-1,convert(date, a.CHARGE_MONTH+'01', 112))
            ,year(dateadd(month,-1,convert(date, a.CHARGE_MONTH+'01', 112)))
)

    INSERT INTO @results (
      [billing_date],
      [year],
      [type],
      [dollars],
      [units],
      [CC],
      [offering],
      [IntegratedReleasePlanNm],
      [ProjectId],
      [ProjectNm],
      [ModelEstimateId],
      [query],
      [ItemGroupId],
      [CashflowType]
      )
      select 
        * 
      from 
        forecast_baseline

    INSERT INTO @results (
      [billing_date],
      [year],
      [type],
      [dollars],
      [units],
      [CC],
      [offering],
      [IntegratedReleasePlanNm],
      [ProjectId],
      [ProjectNm],
      [ModelEstimateId],
      [query],
      [ItemGroupId],
      CashflowType
      )
      SELECT 
        b.datetimemonth
        ,year([billing_date])
        ,'Baseline'
        ,[dollars]
        ,[units]
        ,CC
        ,[offering]
        ,'Baseline'
        ,'projected'
        ,'projected'
        ,'projected'
        ,'projected'
        ,'N/A'
        ,'N/A'
      FROM 
        forecast_baseline a inner join yearsinmonths b 
          on cast(year([billing_date]) as char(4))+ RIGHT('00' + CONVERT(VARCHAR,month([billing_date])), 2) = @monthkey
         and b.datetimemonth > [billing_date]
      return
  end