Search code examples
angularjsangularjs-service

Why can't I access a method inside AngularJS service after "then" promise? (see code)


I get the following error: TypeError: Object [object global] has no method 'setApiToken'

angular.module("userService", ["restangular", "angular-cache"]).factory "userService", (Restangular, $angularCacheFactory) ->

 setCurrentUserId: (value) ->
     # Code here...

 login: (user, callback) ->
  # FOR TESTING PURPOSES, I DON'T GET AN ERROR HERE
  @setApiToken(1)
  Restangular.all("sessions").post(user).then (returnVal) ->
    returnJson = angular.fromJson(returnVal)

    if returnJson.success is true
      # I GET AN ERROR HERE ############################################
      @setApiToken(returnJson.data.authToken)
      returnJson.id
    else
      ""

Solution

  • @SLaks is right. You need a fat arrow to keep this in scope on your callback to then(). Also, you shouldn't need to parse the JSON response, that should be handled by Restangular.

    angular.module("userService", ["restangular", "angular-cache"]).factory "userService", (Restangular, $angularCacheFactory) ->
    
     setCurrentUserId: (value) ->
         # Code here...
    
     login: (user, callback) ->
      # FOR TESTING PURPOSES, I DON'T GET AN ERROR HERE
      @setApiToken(1)
      Restangular.all("sessions").post(user).then (returnVal) =>
        returnJson = angular.fromJson(returnVal)
    
        if returnJson.success is true
          # I GET AN ERROR HERE ############################################
          @setApiToken(returnJson.data.authToken)
          returnJson.id
        else
          ""