我有一些问题需要理解服务处理承诺中的行为。在下面的代码中,我有一个异步调用服务器。尝试在.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不会更新。
感谢您的帮助!
答案 0 :(得分: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
)