Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>When communicating with API, I would recommend the following approach to structuring your services (as <a href="https://stackoverflow.com/a/11850027/1095616">advised by Misko Hevery</a>):</p> <pre><code> // 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; }); }); } } ] ); </code></pre> <p>But for sure, I would also advise against fetching all this data in separate calls. Instead, if possible, you should have your API return you the combined JSON. Server-side combining would be many times faster.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload