Dan Kanze
Dan Kanze

Reputation: 18595

angular ngResource response object not accessible in service

angular.module('myApp.services', ['ngResource']).
  factory('Imgur', function($resource, $http) {

    $http.defaults.useXDomain = true;
    $http.defaults.headers.common['Authorization'] = 'Client-ID 123123123123';

    var albumsService = {};

    var albums = $resource('https://api.imgur.com/3/account/me123/albums').get();

    //I can access albums.data in ng-repeate in view, but not here?
    //returns undefined
    console.log(albums.data);

    albumsService.albums = function() {
      return albums;
    };

    return albumsService;
  });

Using this works

  <ul class="nav nav-pills">
    <li ng-repeat="album in imgur.albums().data">
      {{album.title}}
    </li>
  </ul>

Upvotes: 1

Views: 615

Answers (1)

Noah Freitas
Noah Freitas

Reputation: 17430

In order to use the albums information inside your service, pass a callback to get():

var albums = $resource('https://api.imgur.com/3/account/me123/albums').get(function () {
    // Log out all the titles.
    albums.data.forEach(function (album) {
        console.log(album.title);
    });
});

Upvotes: 3

Related Questions