我有两个网络服务:
像这样返回“文章”:
[
{
"id": "1",
"headline": "some text",
"body": "some text",
"authorId": "2"
},
{
"id": "2",
"headline": "some text",
"body": "some text",
"authorId": "1"
}
]
另一个返回一个像这样的“作者”,给定一个 id:
{
"id": "1",
"name": "Test Name",
"email": "test@test.com",
"photo": "path/to/img"
}
我想将两者结合起来,这样我就可以在文章概述列表中显示作者姓名和照片。
像这样:
[
{
"id": "1",
"headline": "some text",
"body": "some text",
"authorId": "2",
"author_info": {
"id": "2",
"name": "Another Test Name",
"email": "test2@test.com",
"photo": "path/to/img"
}
},
{
"id": "2",
"headline": "some text",
"body": "some text",
"authorId": "1"
"author_info": {
"id": "1",
"name": "Test Name",
"email": "test@test.com",
"photo": "path/to/img"
}
}
]
我有一个获取文章的“文章”服务,但是在返回“文章”服务输出之前,使用来自类似“作者”服务的作者信息来丰富返回的 JSON 的最佳方法是什么?
factory('Authors', ['$http', function($http){
var Authors = {
data: {},
get: function(id){
return $http.get('/api/authors/' + id + '.json')
.success(function(data) {
Authors.data = data;
})
.error(function() {
return {};
});
}
};
return Authors;
}]).
factory('Articles', ['$http', 'Authors', function($http, Authors){
var Articles = {
data: {},
query: function(){
return $http.get('/api/articles.json')
.success(function(result) {
Articles.data = result; // How to get the author info into this JSON object???
})
.error(function() {
Articles.data = [];
});
}
};
return Articles;
}])
还请告诉我这是否是一种完全错误的方法。 :)
最佳答案
在与 API 通信时,我建议使用以下方法来构建您的服务(如 advised by Misko Hevery):
// Author model/service
angular.module('myApp').factory('Author', function($http) {
var Author = function(data) {
angular.extend(this, data);
};
Author.get = function(id) {
return $http.get('/authors/' + id).then(function(response) {
return new Author(response.data);
});
};
return Author;
});
// Article model/service
angular.module('myApp').factory('Article', function($http) {
var Article = function(data) {
angular.extend(this, data);
};
Article.query = function() {
return $http.get('/articles/').then(function(response) {
var articles = [];
angular.forEach(response.data, function(data){
articles.push(new Article(data));
});
return articles;
});
};
return Article;
});
// Your controller
angular.module('myApp')
.controller('Ctrl'
,[
'$scope'
,'Article'
,'Author'
,function($scope, Article, Author){
Article.query()
.then(function(articles){
$scope.articles = articles;
attachAuthors(articles);
});
function attachAuthors(articles){
angular.forEach(articles, function(article){
Author.get(article.authorId)
.then(function(author){
article.author = author;
});
});
}
}
]
);
但可以肯定的是,我也建议不要在单独的调用中获取所有这些数据。相反,如果可能,您应该让 API 返回组合的 JSON。服务器端合并会快很多倍。
关于ajax - AngularJS 结合 Web 服务响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15011186/