0

I am having some problems to understand the behaviour inside a service handing promises. In the following code i have one async call the server. Trying to use @$rootScope in the .then call is not possible. But assigning @$rootScope to an attribute in the class _rs does the trick. And i don't get why?

namespace( 'com.myapp.service'

  SessionService:

    class SessionService

      _rs = null
      _this = null

      # Specify expected constructor services
      @$inject  : ["$rootScope", "$log", "User" ]

      constructor : (@$rootScope, $log, @User) ->
        # Scope binding and this interpolation
        _rs = @$rootScope
        _this = @

        $log.debug("Calling constructor of SessionService")
        @currentUser = ""

        @initCurrentUser()

        return this

      loadCurrentUser : () ->
        return serverFunctions().func('sessionService').loadCurrentUser("async")

      initCurrentUser : () ->
        result = @loadCurrentUser()

        result.then (res) ->
          _rs.$apply ->
            _this.currentUser = "test"

        result.fail (e) ->
          _rs.$apply ->
            console.error(e)

      # Returns current user
      getCurrentUser: () ->
        return _this.currentUser
)

Furthermore its not working when i use @currentUser instead of _this.currentUser in the getCurrentUser method. The UI in the controllers is just not updating.

Thanks for your help!

Alebon
  • 1,189
  • 2
  • 11
  • 24
  • Ok, found it out by myself: http://stackoverflow.com/questions/8965855/coffeescript-when-to-use-fat-arrow-over-arrow-and-vice-versa *DOH* – Alebon Sep 23 '13 at 14:39
  • I think I'd approach this with a $watch in current scope on a property of the service object. – jcollum Sep 23 '13 at 17:19

1 Answers1

0
namespace( 'com.myapp.service'

  SessionService:

    class SessionService

      # Specify expected constructor services
      @$inject  : ["$rootScope", "$log", "User" ]

      constructor : (@$rootScope, $log, @User) ->

        $log.debug("Calling constructor of SessionService")
        @currentUser = ""

        @initCurrentUser()

        return this

      loadCurrentUser : () ->
        return serverFunctions().func('sessionService').loadCurrentUser("async")

      initCurrentUser : () =>
        result = @loadCurrentUser()

        result.then (res) =>
          @$rootScope.$apply =>
            @currentUser = "test"

        result.fail (e) =>
          @$rootScope.$apply =>
            console.error(e)

      # Returns current user
      getCurrentUser: () =>
        return @currentUser
)
Alebon
  • 1,189
  • 2
  • 11
  • 24