Reputation: 1650
So I am trying to start using Angular services to fetch the data for me.
Currently I have this service to get a medium from my rails server:
angular.module('Test').factory 'MediaShow', ($resource, $http, $routeParams) ->
class Comments
constructor: (errorHandler) ->
@service = $resource('/media/:id.json',
{id: $routeParams.id},
{'query': { method: 'GET', isArray: false }}
)
@errorHandler = errorHandler
defaults = $http.defaults.headers
defaults.patch = defaults.patch || {}
defaults.patch['Content-Type'] = 'application/json'
create: (attributes, successHandle) ->
new @service
new @service(list: attributes).$save ((list) -> successHandler(list)), @errorHandler
all: ->
@service.query((-> null), @errorHandler)
And here I attempt to use the all()
function in one of my controllers:
$scope.init = ->
@mediumService = new MediaShow(serverErrorHandler)
requestedData = @mediumService.all()
$scope.medium = requestedData.medium
console.log($scope.medium)
keys = []
for key of requestedData
keys.push key
console.log(keys)
And here is how it all looks in my console:
So as you can see, the medium object does exist in the data that I fetched from the server. But for some reason I am not able to access it.
What am I doing wrong here?
Upvotes: 0
Views: 29
Reputation: 239312
The key medium
doesn't appear in your output, because it doesn't exist at the point you generate that output. The property medium
will appear at some point after your console log, when the AJAX request actually completes.
The property does exist in the console's object explorer, because that is updated dynamically as the object changes. It will always show the current state of the object.
I know absolutely nothing about Angular, but your all
method seems to be returning a promise. You almost certainly need to wait for that promise to complete, and then access the data in medium
.
Something like:
scope.init = ->
@mediumService = new MediaShow(serverErrorHandler)
requestedData = @mediumService.all()
requestedData.done (data) =>
$scope.medium = data.medium
console.log($scope.medium)
keys = []
for key of requestedData
keys.push key
console.log(keys)
Upvotes: 1