无法在Angular服务中存储值值

时间:2014-07-18 17:13:15

标签: angularjs

我试图在AngularJS中构建会话服务,但我在将值存储在其中时遇到了问题。 我存储或获取值错误吗? 我试图实施的模式由Gert Hengeveld在他的文章Techniques for authentication in AngularJS applications中描述

应用/资产/ Javascript角/应用/控制器/ SessionCtrl.js.coffee

app = angular.module "my_app"
app.controller 'SessionCtrl', ['$scope', 'Session', '$http', '$window', 
($scope, Session, $http, $window) ->


  getUserToken = (username, password) ->
    params = { grant_type: "password", username: username }

    $http(
      method: "POST"
      url: "http://app.dev/oauth/token"
      params: params
    ).success((data, status, headers, config) ->
      console.log('getUserToken ' + data.access_token) // Outputted with the token I received.
      Session.create(data.access_token)
    ).error (data, status, headers, config) ->


  $scope.hi_there = 'martin'

服务/ session.js

app = angular.module('trenger')
app.service('Session', function () {
    this.create = function (accessToken) {
      console.log('in Sesssion create: ' + accessToken); // Seen in the console
      this.accessToken = accessToken;
    };
    this.destroy = function () {
      this.accessToken = null;
    };
    console.log('accessToken seen from the service: ' + this.accessToken ); // Not seen in console
    return this;
  });

application.html

      <strong> Session.accessToken {{ Session.accessToken }}  </strong> # Nothing
      <em>     Other val from SessionCtrl: {{ hi_there }}     </em>     # This works

1 个答案:

答案 0 :(得分:4)

userId是属性,而不是函数,因此

  console.log(Session.userId)

会更好。