【问题标题】:Restangular data, getting into $scope for a listRestangular 数据,进入 $scope 以获取列表
【发布时间】:2015-01-08 15:53:25
【问题描述】:

整天都在与 API 打交道,因此决定使用 Restanglar。将数据导出并导入 $scope 确实存在问题。

我知道它不仅仅是从 API 返回的 JSON,还有许多其他内部方法等。但是当我把数据拿出来时,我可以看到它隐藏在控制台调试的某个地方.log,但我似乎无法将它放入 $scope 以在我之前运行良好的视图中使用它。

如何将这些数据导出到我的 $scope 以及我的视图中?

型号

angular.module('horse', ['restangular'])
    .config(function(RestangularProvider) {
        RestangularProvider.setBaseUrl('http://url/api');

        RestangularProvider.setResponseInterceptor(
          function(data, operation, what) {
            if (operation == 'getList') {
              return data[what];
            }
            return data;
        });
});

控制器

angular
  .module('horse')
  .controller("IndexController", function ($scope, Restangular) {
    $scope.horse = null;
    $scope.showSpinner = true;

    Restangular.all('horse').getList().then(function(horse) {
        $scope.horse = horse;
        console.log($scope.horse);
    });
});

API 响应

{"error":false,"horse":[{"id":"1","name":"horse 2"},{"id":"2","name":"horse 2"}]}

编辑 1

静止角响应

[Object, Object, route: "horse", getRestangularUrl: function, getRequestedUrl: function, addRestangularMethod: function, clone: function…]

编辑 2

我也试过这个 - https://github.com/mgonto/restangular#using-values-directly-in-templates

$scope.horse = Restangular.all('horse').getList().$object;

这只会导致输出一个空数组。我还尝试删除 setResponseInterceptor 并修改 api 的结构以直接生成数据数组而没有元数据(错误等),不高兴:(

【问题讨论】:

    标签: angularjs restangular steroids


    【解决方案1】:

    数据似乎正在通过。我注意到您正在使用 Steroids,您是否检查过标记而不仅仅是控制台?

    确保将范围微调器设置为 false,以确保在数据通过时隐藏微调器。

    $scope.ShowSpinner = false;

    【讨论】:

      【解决方案2】:

      假设您显示为“API 响应”的内容是从控制器中的 console.log 输出的内容,您似乎需要做的就是将您的范围模型设置为响应数据中的属性“horse”像这样:

      $scope.horse = horse.horse;
       

      由于读起来很奇怪,您应该将 .then 回调的参数名称更改为 data,这将是一个更加不可知和标准的参数名称。如果您进行了更改,您可以从回调内部将您的马数据设置为您的范围模型,如下所示:

      $scope.horse = data.horse;

      如果我误解了您的问题,请告诉我。希望这会有所帮助。

      【讨论】:

      • 感谢您的回复,对不起,我应该更清楚,API 响应是我在浏览器中使用 REST 客户端转到相应 URL 时得到的。我现在添加了我从 Restangular 得到的东西,这似乎是一堆其他的东西。我可以看到隐藏在“Restangularized”响应中的数据,但它似乎不容易访问,我不敢相信它很难摆脱,所以我一定是在做一些愚蠢的事情;)
      猜你喜欢
      • 1970-01-01
      • 2014-08-26
      • 1970-01-01
      • 1970-01-01
      • 2021-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多