Hot to return a pure array of objects from AppEngi

2019-05-16 05:57发布

I am doing AppEngine endpoints for a RESTFul backend in AppEngine. I use AngujarJS on the client side, managing server data with ngResource.

My issue: I am not able to return a pure array from AppEngine Endpoint. I tried this:

@ApiMethod(
        name = "mpscorerapi.getAllResults",
        path = "/tournament/{tournamentId}/result/"
        httpMethod = HttpMethod.GET
)
public List<SimpleResult> getAllResults(@Named("tournamentId") Long tournamentId) throws NotFoundException
{
   ...
}

Although this gets the data from the server down to the client, it does not build an array of "SimpleResult" objects, but a single object than contains an array of SimpleResult's, called "items":

  {
 "items": [
  {
   "id": "5733953138851840",
   "h": 0,
   "r": 0,
   "kind": "mpscorer#mpscorerapiItem"
  },
  {
   "id": "5733953138851841",
   "h": 1,
   "r": 2,
   "kind": "mpscorer#mpscorerapiItem"
  }
 ],
 "kind": "mpscorer#mpscorerapi",
 "etag": "\"SALE0WnK41Jo38zV0ILO62-rVOI/Mh2G6GGztZv-wj_56Kjf1o1XBaM\""
}

This makes ngResource pretty useless, because the "query" method expects a pure array as reply:

$scope.resultsSrv = Result.query({tournamentID:tournamentId}) //fails!!!!

Any idea on how to get just the "SimpleResult" array?

Thanks!

2条回答
ゆ 、 Hurt°
2楼-- · 2019-05-16 06:32

I had a similar challenge. I ended up using jQuery to parse it out. Using map it is very straight forward.

My case was:

$.map(locs.items, function (loc) {
                      return {
                          value: loc.longName
                      };
查看更多
倾城 Initia
3楼-- · 2019-05-16 06:43

You have to transform the request, for example as follows:

angular.module('myApp')
  .factory('Result', function Result($http, $resource) {
    var Result = $resource('/tournament/:tournamentId/result/', {}, {
      query: {
        method: 'GET', 
        isArray: true,
        transformResponse: [].concat($http.defaults.transformResponse, function transformResponse(data) {
          return data.items;
        })
      }
    });
    return Result;
  });
查看更多
登录 后发表回答