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