使用ng-repeat检索AngularJS中的帖子(模型关系)与restful Api的注释

时间:2014-04-26 15:58:29

标签: angularjs rest ngresource

编辑:我已经决定使用Restangular,因为看起来Lodash库与AngularJS相当不错。我还有一个问题。 Restangular的getList()函数期望响应是一个数组,但我的服务器响应包括两个参数,其中只有一个是数组。像这样:

{"error": "false", "topics": [{"id":"1", "title":"someTitle"},{"id":"2", "title":"someTitle2"}]}

我假设我会在RestangularProvider.setResourceInterceptor中设置它,但我不太确定如何。任何选择?我能够从一个.json文件中读取响应,我创建了一个数组,所以至少我知道我正在读它。 :)

更新:我尝试了这个,但我得到:TypeError:无法设置属性'元数据'未定义的

RestangularProvider.addResponseInterceptor(function (data, operation, what, url, response, deferred) {
  var newResponse;
  // This is a get for a list
  if (operation === "getList") {
    // First the newResponse will be response.topics which is actually an array
    newResponse = response.topics;
    // Then we add to this array a special property containing the metadata for paging for example
    newResponse.metadata = response.data.meta;
  } else {
    // If it's an element, then we just return the "regular" response as there's no object wrapping it
   newResponse = response;
  }
  return newResponse;
});

< --------------------------------------------- -------------------------------------------------- --------------------------------->

我对angularJS很新,但仍然不确定CRUD操作的几个方面。我听过很多赞美ngResource,但也建议$ http更适合更复杂的模型关系。我在这里有一个具体的问题,我想知道是否有人能指出我正确的方向。对于这个例子,我选择使用ngResource,虽然我不太确定我对它的数据处理有多喜欢。我的Api,主题和评论有两个资源。 Api端点如下:

http://api.example.com/v1/topics //To get all topics
http://api.example.com/v1/topics/:id //To get a single topic
http://api.example.com/v1/topics/:id/comments //To get all comments for a single topic

我已经编写了以下代码来获取主题:

app.controller("mainController", function($scope, $resource, $location, $http, localStorageService, requestNotification) {

  var Topic = $resource('http://api.discussorama.com/v1/topics/:id', {id: '@id'}, {
    query: {
        isArray: false,
        method: 'GET',
        headers: {'X-Api-Secret': 'xxx', 'Authorization': 'xxx', 'Content-Type': 'application/x-www-form-urlencoded'}
    }
  });

  var topics = Topic.query();
  topics.$promise.then(function(data){
    $scope.topics = data.topics;
  });

});

然后在我的视图中使用它(没有问题):

<div ng-repeat="t in topics | orderBy:'created_at':true" class="topic">
  <div class="row">
    <div class="col-md-6 topic_body">
      <h3 class="topic_title">{{ t.topic_title }}</h3>
      <h5 class="topic_subtitle">Posted by {{ t.name }}</h5>
      <hr>
      <img ng-src="{{ t.image_url }}" class="img-responsive"/>
      <p class="topic_content">{{ t.topic_content }}</p>  
    </div>
    <div class="col-md-6">
      <img ng-src="{{ t.profile_pic }}" width="60px"/>
    </div>
  </div>
  <hr>
</div>

我现在要做的是在主题的ng-repeat中查询注释Api端点,以显示该特定主题的注释。有没有办法从ng-repeat中传递t.id来替换http://api.example.com/topics/:id/comments中的:id,我该如何解决这个问题。我也会更好地使用$ http或ngResource这个工作的好模块。提前谢谢。

1 个答案:

答案 0 :(得分:0)

所以经过大量的回顾,我至少得知了原来问题的答案。而angularjs确实能够很好地处理它。基本上,通过将ng-controller添加到具有ng-repeat的项目,您现在可以逐项播放项目。如果有人感兴趣,我的解决方案的完整示例代码如下。

//index.html

<!doctype html/>
<html ng-app="restApp" ng-controller="mainController">
  <head>
    <title>Get Comments from Topic</title>
  </head>
  <body>
    <div ng-repeat="topic in topics" ng-controller="topicController">
      <h1>{{ topic.topic_title }}</h1>
      <div ng-repeat="comment in comments">
        <h3>{{ comment.comment }}</h3>
        <p>{{ comment.author_name }}</p>
      </div>
    </div>
    <script type="text/javascript" src="js/lodash.min.js"></script>
    <script type="text/javascript" src="js/angular.min.js"></script>
    <script type="text/javascript" src="js/restangular.js"></script>
    <script type="text/javascript" src="app.js"></script>
  </body>
</html>

我的控制器:

// app.js

var app = angular.module("restApp", ["restangular"]);

app.config(
  function(RestangularProvider){
    RestangularProvider.setBaseUrl('http://api.example.com/v1');
    RestangularProvider.setDefaultHeaders({"Authorization": "..."});
  }
);

app.config(function($httpProvider) {
  $httpProvider.defaults.useXDomain = true;
  delete $httpProvider.defaults.headers
    .common['X-Requested-With'];
});

app.controller("mainController", ["Restangular","$scope", function(Restangular, $scope){
  $scope.message = "Welcome to REST";
  var topics = Restangular.all('topics');
  var allTopics = topics.getList().then(function(topics){
    $scope.topics = topics;
    console.log($scope.topics);
  });
}]);

app.controller("topicController", ["Restangular", "$scope", function(Restangular, $scope){
  var oneTopic = Restangular.one('topics', $scope.topic.id);
  oneTopic.get().then(function(topic) {
    topic.getList('comments').then(function(comments){
      $scope.comments = comments;
      console.log($scope.comments);
    });
  });
}]);

如果有人从Restangular.getList()的对象响应中提取数组有任何成功,请告诉我。目前我已经添加了一个版本的API,它将响应作为数组发送,以解决此问题。