Meteor - Call function before state loaded using ui-router

僤鯓⒐⒋嵵緔 提交于 2019-12-12 03:43:27

问题


We're making a meteor app using angular and ui-router to control the states. We want to show a promo site if the user doesn't have access to the main part of the site. There will be a flag on the user's document in the User collection in mongodb as to whether they have access or not.

How would we direct to this promo state before a state is loaded if they don't have access? The basic flow would be calling a function to check whether they have access, and then loading a state based on that.


回答1:


In the route for the protected page (or in my case the parent of a set of protected pages), put this:

    .state('app', {
      abstract: true,
      template: '<mymenu></mymenu>',
      controller: Menu,
      resolve: {
        currentUser: ($q) => {
          var deferred = $q.defer();

          Meteor.autorun(function () {
            if (!Meteor.loggingIn()) {
              if (Meteor.user() == null) {
                deferred.reject('AUTH_REQUIRED');
              } else {
                deferred.resolve(Meteor.user());
              }
            }
          });

          return deferred.promise;
        }
      }
    });

The resolve part will reject the route (see below for the handler), and also ensure that Meteor.user() is fully loaded before activating the route.

Put this handler in your .run method:

function run($rootScope, $state) {
  'ngInject';

  $rootScope.$on('$stateChangeError',
    (event, toState, toParams, fromState, fromParams, error) => {
      console.log("$stateChangeError: "+error);
      if (error === 'AUTH_REQUIRED') {
        $state.go('login');
      }
    }
  );
}

It will redirect you to the login page (or any other page of your choice)



来源:https://stackoverflow.com/questions/39774910/meteor-call-function-before-state-loaded-using-ui-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!