0

编辑:我决定使用 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 是这个工作的好模块。提前致谢。

4

1 回答 1

0

因此,经过大量环顾四周后,我至少知道了我最初问题的答案。并且 angularjs 确实可以很好地处理它。基本上,通过使用 ng-repeat 将 ng-controller 添加到项目中,您现在可以逐项处理项目。如果有人感兴趣,下面是我的解决方案的完整示例代码。

//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 版本,它以数组的形式发送响应来解决这个问题。

于 2014-04-27T06:47:18.090 回答