Reputation: 1761
I have an angular factory in coffeescript like so :
angular.module('app').factory 'appFactory', ['$q', 'Api', 'Flash', ($q, Api, Flash) ->
obj = undefined
get = ->
if angular.isDefined(obj)
return $q.when(obj)
Api.AppInitializer.query().$promise.then ((response) ->
obj = response
return obj
)
{
get: get()
}
]
And I'm calling it from a controller like so:
angular.module('app').controller 'appCtrl', ($scope, appFactory) ->
appFactory.get.then ((data) ->
$scope.obj = data
)
Basically I'm fetching data from a factory, and if the data is currently undefined I'll make an Api request to fetch the data. This works as intended.
Now I need to pass a token params into the factory to fetch a specific record:
angular.module('app').factory 'appFactory', ['$q', 'Api', 'Flash', ($q, Api, Flash) ->
obj = undefined
get = (token) ->
if angular.isDefined(obj)
return $q.when(obj)
Api.AppInitializer.get(token: token).$promise.then ((response) ->
obj = response
return obj
)
{
get: get()
}
]
And I'm calling it from a controller like so:
angular.module('app').controller 'appCtrl', ($scope, appFactory) ->
token = $scope.current_user.token_id
appFactory.get(token).then ((data) ->
$scope.obj = data
)
Now I'm getting the error
TypeError: appFactory.get is not a function
How do I pass the token parameter to appFactory.get?
Upvotes: 1
Views: 475
Reputation: 171669
Several problems.
get()
in factory when you assign it to the
returned objectYou can store the request promise and return that without needing to use $q
angular.module('app').factory 'appFactory', ['$q', 'Api', 'Flash', ($q, Api, Flash) ->
promise = undefined
get = (token) ->
if !angular.isDefined(obj)
promise = Api.AppInitializer.get(token: token).$promise
return promise
{
get: get
}
]
I don't use coffee so syntax may be off a bit
Upvotes: 1
Reputation: 136144
You missed to return promise of Api.AppInitializer
method when data exists.
Code
get = (token) ->
if angular.isDefined(obj)
return $q.when(obj)
//return promise so that you can put .then inside controller.
return Api.AppInitializer.get(token: token).$promise.then ((response) ->
obj = response
return obj
)
//return factory object as well
return {
get: get //assign reference of get method here.
}
Upvotes: 1