Kurt Mueller
Kurt Mueller

Reputation: 3224

Storing an ngResource call into a variable

I'm writing an app that uses Rails to serve up a JSON api. I'm using the Angular ngResource module to consume those json endpoints.

While I have ngResource, configured correctly (see below) and can store its results into a $scope variable or log it out to the console, I'm having a difficult time using a service to make a ngResource call and have it store its results into a regular old array variable.

In this example, I have a resource called Genre, which accesses my Rails JSON api. GenreService injects Genre and attempts to make a 'Genre.index()call and store those results into a localArray` variable.

Here are the file contents:

Genre.js.coffee

'use strict'

app = angular.module("ATWP")

app.factory "Genre", ($resource) ->
  $resource "/genres/:slug",
    slug: "@slug"
  ,
    create:
      method: "POST"

    index:
      method: "GET"
      isArray: true

    show:
      method: "GET"

    update:
      method: "PUT"

    books:
      method: "GET"

GenreService.js.coffee

'use strict'

app = angular.module('ATWP')

genreService = app.factory 'GenreService', (Genre) ->

  genreResponse = new Array()

  Genre.index((response) ->
    genreResponse = response
  )

  console.log 'Genre Response'
  console.log genreResponse

  getGenres: ->
    genreResponse

Logging genreResponse at this point in time will will actually show an array. However, if I inject GenreService into a controller and then store the result of the GenreService.getGenres() into an array, that array will appear empty whenever I log it to the console.

I'm wondering why that is the case. Do I have to use the Promise API? Can anybody help me why understand this is happening?

Thanks guys.

Upvotes: 0

Views: 254

Answers (1)

Foo L
Foo L

Reputation: 11137

When console.log genreResponse, the call hasn't completed yet, so you will have an empty array.

Try using a $watch instead (non-coffeescript):

$scope.$watch('genreResponse', function (newVal, oldVal) {
  if (newVal) {
    console.log($scope.genreResponse);
  }
});

Upvotes: 1

Related Questions