【问题标题】:AngularJS scope of THIS in Factory工厂中 THIS 的 AngularJS 范围
【发布时间】:2015-06-30 09:34:56
【问题描述】:

因为 'this' 属性,我很困惑。

AuthenticationFactory 中的“delete this.user;”是什么意思。我认为函数“check”是一种方法,因此它将与“auth”对象绑定。但是,“auth”对象中没有“user”属性。能解释一下吗?

另外,在“UserAuthFactory”中(delete AuthenticationFactory.user,delete AuthenticationFactory.userRole)

我不知道什么是“user”和“userRole”属性。 AuthenticationFactory 中没有此类属性。

这是来自http://thejackalofjavascript.com/architecting-a-restful-node-js-app/的我的代码

myApp.factory('AuthenticationFactory', function($window) {
  var auth = {
    isLogged: false,
    check: function() {
      if ($window.sessionStorage.token && $window.sessionStorage.user) {
        this.isLogged = true;
      } else {
        this.isLogged = false;
        delete this.user;
      }
    }
  }

  return auth;
});

myApp.factory('UserAuthFactory', function($window, $location, $http, AuthenticationFactory) {
  return {
    login: function(username, password) {
      return $http.post('http://localhost:3000/login', {
        username: username,
        password: password
      });
    },
    logout: function() {

      if (AuthenticationFactory.isLogged) {

        AuthenticationFactory.isLogged = false;
        delete AuthenticationFactory.user;
        delete AuthenticationFactory.userRole;

        delete $window.sessionStorage.token;
        delete $window.sessionStorage.user;
        delete $window.sessionStorage.userRole;

        $location.path("/login");
      }

    }
  }
});

【问题讨论】:

    标签: javascript angularjs this factory


    【解决方案1】:

    如果你再往下看,控制器代码:

    $scope.login = function() {
    
      var username = $scope.user.username,
        password = $scope.user.password;
    
      if (username !== undefined && password !== undefined) {
        UserAuthFactory.login(username, password).success(function(data) {
    
          AuthenticationFactory.isLogged = true;
          AuthenticationFactory.user = data.user.username;
          AuthenticationFactory.userRole = data.user.role;
    
          $window.sessionStorage.token = data.token;
          $window.sessionStorage.user = data.user.username; // to fetch the user details on refresh
          $window.sessionStorage.userRole = data.user.role; // to fetch the user details on refresh
    
          $location.path("/");
    
        }).error(function(status) {
          alert('Oops something went wrong!');
        });
      } else {
        alert('Invalid credentials');
      }
    
    };
    

    成功登录后,控制器会将属性user 和userRole 添加到AuthenticationFactory。

    【讨论】:

      猜你喜欢
      • 2013-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多