【问题标题】:Restangular: getList with object containing embedded arrayRestangular:带有包含嵌入式数组的对象的getList
【发布时间】:2015-03-18 08:02:39
【问题描述】:

在我的 AngularJS 项目中,我尝试使用 Restangular getList 方法,但它返回错误,因为 API 响应不是直接的数组而是包含数组的对象。

{
  "body": [
    // array elements here
  ],
  "paging": null,
  "error": null
}

Restangular 错误消息是:

Error: Response for getList SHOULD be an array and not an object or something else

是否可以告诉 Restangular 它正在寻找的数组在 body 属性内?

【问题讨论】:

    标签: angularjs restangular


    【解决方案1】:

    是的,请参阅Restangular documentation。你可以像这样配置 Restangular:

    rc.setResponseExtractor(function(response, operation) {
        if (operation === 'getList') {
            var newResponse = response.body;
            newResponse.paging = response.paging;
            newResponse.error = response.error;
            return newResponse;
        }
        return response;
    });
    

    编辑:现在看来 Restangular 的 API 发生了变化,变得更好了,当前使用的方法是 addResponseInterceptor。可能需要对传递的函数进行一些调整。

    【讨论】:

    • 新用法现在看起来像:RestangularProvider.addResponseInterceptor(function (data, operation, what, url, response, deferred) {
    • 如果您想避免更改所有 API 调用的 Restangular 配置,您可以创建并使用自定义配置,as described in the docs
    【解决方案2】:

    我认为你应该使用来自Custom Methods的customGET

    Restangular.all("url").customGET(""); // GET /url and handle the response as an Object

    【讨论】:

    • 如果只有一个 API 调用返回一个对象,这是一个很好的解决方案。使您不必在全局范围内更改 Restangular 的配置,也不必为孤立的用例创建自定义配置(在工厂中)。
    • 如果您使用 solr 并返回一些您需要保留的记录(而使用带有 getlist 的拦截器,您仍然需要删除它),这也可以工作
    【解决方案3】:

    Collin Allen 建议您可以像这样使用addResponseInterceptor

        app.config(function(RestangularProvider) {
    
            // add a response intereceptor
            RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
              var extractedData;
              // .. to look for getList operations
              if (operation === "getList") {
                // .. and handle the data and meta data
                extractedData = data.body;
                extractedData.error = data.error;
                extractedData.paging = data.paging;
              } else {
                extractedData = data.data;
              }
              return extractedData;
            });
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-19
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      相关资源
      最近更新 更多