getCurrentUser()。在DaftMonk /发电机角fullstack未定义的角色 [英] getCurrentUser().role undefined in DaftMonk/generator-angular-fullstack

查看:213
本文介绍了getCurrentUser()。在DaftMonk /发电机角fullstack未定义的角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用一个谟的DaftMonk / AngularJS全栈发生器。生成的code包含逻辑来管理用户(注册,登录,角色等),这是伟大的。但是,存在使用code和当前用户的角色时的一个问题是有时未定义

We are using the DaftMonk/AngularJS Full-Stack generator for a projet. The generated code contains the logic to manage users (registration, login, roles, etc.), which is great. However, there is an issue when using the code and the role of the current user is sometimes undefined.

我们遇到的问题,因为我们要实现一个简单的功能:登录/注册之后,用户应该被重定向到依赖于他的角色的URL。例如,老师用户应该被重定向到 / teacherHome 学生用户应该被重定向到 / studentHome 。由于Auth.getCurrentUser()的作用是不确定的,逻辑是行不通的。

We encountered the issue as we wanted to implement a simple feature: after login/signup, the user should be redirected to a URL that depends on his role. For instance, 'teacher' users should be redirected to /teacherHome and 'student' users should be redirected to /studentHome. Because Auth.getCurrentUser().role is undefined, the logic does not work.

如何重现该问题

要重现该问题,请编辑客户端/应用/帐号/登录/ login.controller.js 文件,并添加语句记录Auth.getCurrentUser的值() 。角色,就像这样:

To reproduce the issue, edit the client/app/account/login/login.controller.js file and add statements to log the value of Auth.getCurrentUser().role, like so:

...
  if(form.$valid) {
    Auth.login({
      email: $scope.user.email,
      password: $scope.user.password
    })
    .then( function() {
      // Logged in, redirect to home
      console.log("Current user role: " + Auth.getCurrentUser().role);
      $location.path('/');
    })
    .catch( function(err) {
      $scope.errors.other = err.message;
    });
  }
};
...

在测试此code,你会发现,用户角色在此阶段不。后来,然而,它被分配一个值。这表明,该问题可能与一个异步REST调用

When testing this code, you will find out that the user role is undefined at this stage. Later on, however, it is assigned a value. This suggests that the issue might be related to an asynchronous REST call.

推荐答案

其实有几个相关的问题以及如何解决这些问题。

There are actually a couple of related issues and ways to fix them.

解决方法1:使用所提供的 Auth.isLoggedInAsync 函数

Solution 1: use the provided Auth.isLoggedInAsync function

该验证模块,生成的code的一部分,提供了一种方法来检查,如果在登录过程已经完成(以及调用回调函数如果是这种情况)。因此,要解决这个问题的一种方法是在客户端code使用此功能,就像这样:

The Auth module, part of the generated code, provides a method to check if the login process has been completed (and to invoke a callback function when this is the case). So, one way to fix the issue is to use this function in the client code, like so:

  if(form.$valid) {
    Auth.login({
      email: $scope.user.email,
      password: $scope.user.password
    })
    .then( function() {
      // Logged in, redirect to home
      console.log("Current user role: " + Auth.getCurrentUser().role);
      Auth.isLoggedInAsync(function(success) {
        console.log("Current user role: " + Auth.getCurrentUser().role);
      });
      $location.path('/');
    })
    .catch( function(err) {
      $scope.errors.other = err.message;
    });
  }
};

在这种情况下,你会在控制台中看到两个语句。第一个将表明Auth.getCurrentUser()。作用仍然是不确定的。第二个将显示它现在有一个值。所以,如果你有想要在登录时执行的逻辑和依赖于用户角色(或其他用户属性),把这个逻辑,你传递给的回调函数Auth.isLoggedInAsync()

In this case, you will see two statements in the console. The first one will show that Auth.getCurrentUser().role is still undefined. The second one will show that it now has a value. So, if you have logic that you want to execute at login time and that depends on the user role (or other user attributes), put this logic in a callback function that you pass to Auth.isLoggedInAsync().

解决方案2:修复的根本原因在 auth.service.js

Solution 2: fix the root cause in the auth.service.js

如果你看一下code在客户端/组件/认证/ auth.service.js ,你会看到有异步$ C的一个问题$ C。问题是,的currentUser = User.get(); 触发异步HTTP调用,而的currentUser 没有立即集(它是一个非阻塞调用)。由于承诺立即解决,客户是铅相信,在登录过程已经完成,所有的用户数据是可用的,而它实际上还是在飞行。

If you look at the code in client/components/auth/auth.service.js, you will see that there is an issue with asynchronous code. The problem is that currentUser = User.get(); triggers an asynchronous HTTP call, and that currentUser is not immediately set (it is a non-blocking call). Since the promise is resolved immediately, clients are lead to believe that the login process has completed and that all user data is available, whereas it is in fact still in flight.

在建议修复,许是传递给 User.get一个回调函数解析()

In the proposed fix, the promise is resolved in a callback function passed to User.get().

  /**
   * Authenticate user and save token
   *
   * @param  {Object}   user     - login info
   * @param  {Function} callback - optional
   * @return {Promise}
   */
  login: function (user, callback) {
    var cb = callback || angular.noop;
    var deferred = $q.defer();

    $http.post('/auth/local', {
      email: user.email,
      password: user.password
    }).
    /* ORIGINAL CODE -- promise is resolved too early
    success(function (data) {
      $cookieStore.put('token', data.token);
      currentUser = User.get();
      deferred.resolve(data);
      return cb();
    }).
    */
    /* PROPOSED FIX -- promise is resolved once HTTP call has returned */
    success(function (data) {
      $cookieStore.put('token', data.token);
      currentUser = User.get(function() {
        deferred.resolve(data);
        return cb();
      });
    }).
    error(function (err) {
      this.logout();
      deferred.reject(err);
      return cb(err);
    }.bind(this));

    return deferred.promise;
  },

相关问题并修复

建议code解决的一个问题。现在可以将用户重定向到成功登录后的特定页面。然而,类似的问题在注册过程之后产生的。在这种情况下, Auth.getCurrentUser()作用未定义一段时间(足够长的重定向逻辑失败)。

The proposed code fixes one issue. It is now possible to redirect the user to a specific page upon successful login. However, a similar problem arises after the signup procedure. In this case also, Auth.getCurrentUser().role is undefined for a while (long enough for the redirection logic to fail).

在此情况下,code的固定如下:

In this case, the code was fixed as follows:

  /**
   * Create a new user
   *
   * @param  {Object}   user     - user info
   * @param  {Function} callback - optional
   * @return {Promise}
   */
  createUser: function (user, callback) {
    var cb = callback || angular.noop;

     /* ORIGINAL CODE ---------------------
     return User.save(user,
      function(data) {
        $cookieStore.put('token', data.token);
        currentUser = User.get();
        return cb(user);
      },
      function(err) {
        this.logout();
        return cb(err);
      }.bind(this)).$promise;
       --------------------- */

    /* PROPOSED FIX --------------------- */
    var deferred = $q.defer();
    User.save(user,
      function (data) {
        $cookieStore.put('token', data.token);
        currentUser = User.get(function () {
          console.log('User.save(), user role: ' + currentUser.role);
          deferred.resolve(data);
          return cb(currentUser);
        });
      },
      function (err) {
        this.logout();
        return cb(err);
        deferred.reject(err);
      });
    return deferred.promise;

  },

这篇关于getCurrentUser()。在DaftMonk /发电机角fullstack未定义的角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆