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



EDIT:我决定使用Restangular,因为Lodash库似乎与AngularJS配合得很好。我还有一个问题。Restangular的getList()函数期望响应是一个数组,但是我的服务器响应包括两个参数,其中只有一个是数组。类似这样的东西:

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

我想我会在RestangularProvider.setResourceInterceptor中设置它,但我不太确定如何设置。有什么选择吗?我能够从一个.json文件中读取响应,我制作了一个数组,所以至少我知道我读对了。:)

更新:我尝试过,但我得到了:TypeError:无法设置未定义的属性"metadata"

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来替换中的:idhttp://api.example.com/topics/:id/comments我该怎么做呢。此外,我最好使用$http还是ngResource是这份工作的好模块。提前谢谢。

所以,经过多次环顾,我至少找到了最初问题的答案。angularjs确实处理得很好。基本上,通过将ng控制器添加到具有ng重复的项目中,您现在可以逐个项目地玩这些项目。如果有人感兴趣,下面是我的解决方案的完整示例代码。

//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,它将响应作为数组发送,以解决这个问题。

最新更新