Ryan.lay Ryan.lay - 4 months ago 8
AngularJS Question

Angular1: Factory.method is not a function

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?

Answer

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.
}
Comments