2013-09-23 86 views
0

我在理解服務中承諾的行爲時遇到了一些問題。在下面的代碼中,我有一個異步調用服務器。嘗試在.then調用中使用@ $ rootScope是不可能的。但是將@ $ rootScope分配給類_rs中的一個屬性就可以實現。我不明白爲什麼?AngularJS承諾使用CoffeeScript類處理

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。控制器中的用戶界面不會更新。

感謝您的幫助!

+0

好吧,發現了這件事由我自己:http://stackoverflow.com/questions/8965855/coffeescript-when-to-use-fat-arrow-over-arrow-and-vice-versa * DOH * – Alebon

+0

我想我會通過在服務對象的屬性上的當前作用域中的$ watch來處理此問題。 – jcollum

回答

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 
)