2015-11-14 66 views
0

我的代碼是coffeescript。 我有控制器之間共享會話數據單獨服務:訪問AngularJs中的服務數據

angular.module('cargo').service 'Session', -> 
    this.create = (attributes) -> 
    this.user = attributes 
    return 

我創建一個登錄系統:

angular.module('cargo').factory 'AuthService', ($location, $resource, Session) -> 
    authService = {} 

    authService.login = (credentials) -> 
    sessionResource = $resource('/api/sessions/:id') 
    session = sessionResource.save user: {email: "[email protected]", password: "12345678"}, -> 
     Session.create(session.user) 

    authService.isAuthenticated =() -> 
    !!Session.user.id 

    authService 

的問題是,當我訪問Session.user.id(在authService.isAuthenticated中)爲空。 我試圖用console.log(Session)提示數據,然後我可以看到數據在那裏。它擁有一個具有屬性ID的用戶。但如果我嘗試提示Session.user已經爲空。

有什麼方法可以訪問我錯過的數據嗎?

非常感謝

回答

0

我不熟悉的CoffeeScript但在JS通常我用$ http.post做這樣的身份驗證:

$http.post(my_url, { email: loginEmail, password: loginPassword }); 

在成功回調我得到的訪問令牌,我附加到$ rootScope。

然後,控制器內我可以打電話給我的$資源(聲明爲一個正常的資源)與:

MyService.get({ token: $rootScope.token });