Note that there are some explanatory texts on larger screens.

plurals
  1. POAngularJS combining web service responses
    text
    copied!<p>I have two web services:</p> <p>One returns "Articles" like this:</p> <pre><code>[ { "id": "1", "headline": "some text", "body": "some text", "authorId": "2" }, { "id": "2", "headline": "some text", "body": "some text", "authorId": "1" } ] </code></pre> <p>And the other one returns an "Author" like this, given an id:</p> <pre><code>{ "id": "1", "name": "Test Name", "email": "test@test.com", "photo": "path/to/img" } </code></pre> <p>I want to combine the two, so I can display the authors name and photo in an article overview list.</p> <p>Like this:</p> <pre><code>[ { "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" } } ] </code></pre> <p>I have an "Articles" service that fetches the articles, but what's the best approach for enriching the returned JSON with the author info from the similar "Authors" service before returning the "Articles" service output?</p> <pre><code>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; }]) </code></pre> <p>Please also tell me if this is an entirely wrong approach. :)</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