Meteor - 在使用 ui-router 加载状态之前调用函数 [英] Meteor - Call function before state loaded using ui-router

查看:23
本文介绍了Meteor - 在使用 ui-router 加载状态之前调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在制作一个使用 angular 和 ui-router 来控制状态的流星应用程序.如果用户无权访问网站的主要部分,我们希望显示促销网站.mongodb 的 User 集合中的用户文档上会有一个标志,说明他们是否有权访问.

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.

推荐答案

在受保护页面(或者在我的情况下是一组受保护页面的父级)的路由中,放置:

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;
        }
      }
    });

resolve 部分将拒绝路由(参见下面的处理程序),并确保在激活路由之前 Meteor.user() 已完全加载.

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.

将此处理程序放入您的 .run 方法中:

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)

这篇关于Meteor - 在使用 ui-router 加载状态之前调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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