【问题标题】:AngularJS promise handling with CoffeeScript classAngularJS 承诺处理 CoffeeScript 类
【发布时间】:2013-09-28 09:48:03
【问题描述】:

我在理解服务处理承诺中的行为时遇到了一些问题。在下面的代码中,我有一个异步调用服务器。尝试在 .then 调用中使用 @$rootScope 是不可能的。但是将 @$rootScope 分配给类 _rs 中的属性就可以了。我不明白为什么?

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
)

此外,当我在 getCurrentUser 方法中使用 @currentUser 而不是 _this.currentUser 时,它不起作用。控制器中的 UI 只是没有更新。

感谢您的帮助!

【问题讨论】:

标签: javascript class angularjs coffeescript


【解决方案1】:
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
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-18
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    相关资源
    最近更新 更多