【问题标题】:Angularjs view not displaying data returned from factoryAngularjs视图不显示工厂返回的数据
【发布时间】:2015-06-18 22:56:02
【问题描述】:

我设置了一个使用返回 json 的 rails api 的服务。请求根据控制台输出返回:

Resource {tests: Array[4], $promise: Promise, $resolved: true}

我遇到的问题是我的视图中没有显示任何内容。我是否需要以某种方式转换返回的结果?当我通过邮递员 ping 这条路线时,我得到一个 json 对象作为我的结果集。

我有以下设置:

/service/test.js

  angular.module('myApp')
      .factory('Test', function($resource) {
        return $resource('http://api.myapp-dev.com:3000/tests/:id', { id: '@_id' },
        {
          'index': {
            method:'GET',
            headers: {
              'Authorization':'<a token>'
            },
            isArray: false
          }
    });
  });

/controllers/tests.js

angular.module('myApp')
  .controller('TestsCtrl', function ($scope, Test) {
    $scope.tests = Test.index();
  });

views/tests.html

<div>
  <ul ng-repeat="test in tests">
    <li>{{ test.value }}</li>
  </ul>
</div>

【问题讨论】:

  • 您的工厂正在返回一个承诺对象。你不应该使用thensuccess 解决承诺吗?
  • 感谢您的回复。

标签: javascript ruby-on-rails json angularjs


【解决方案1】:

您应该在控制器中执行以下操作。

Test.index(
  function(response) {
    $scope.tests = response.tests;
  },
  function(error) {
  }
)

还有其他方法可以做到这一点。

Test.index().$promise.then(
  function(response) {
    $scope.tests = response.tests;
  },
  errorCallback
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多