如果用户想访问特定的页面,需要在angular流星中进行登录验证,如何重定向到404页面

How to redirect to 404 page if user wants to access a specific page which requires login authentication in angular-meteor

本文关键字:流星 登录 验证 404页面 重定向 angular 访问 用户 如果      更新时间:2023-09-26

我使用的是Angular Meteor。

我有一个需要登录身份验证的页面。

例如:http://localhost:3000/verifyPhone

我想将用户重定向到:http://localhost:3000/404如果他没有登录并试图访问该受限页面。

这是我的路线文件:

app.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
    $urlRouterProvider.otherwise("/");
    $stateProvider
    .state('verifyPhone', {
      url: "/verifyPhone",
      templateUrl: "client/www/views/verifyPhone.html",
      controller: "SMSVerificationController"
    });
    $locationProvider.html5Mode(true);
});

如何在此处执行重定向?

您可以使用resolve对象来声明对requireUser()的依赖关系:

app.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
    $urlRouterProvider.otherwise("/");
    $stateProvider
    .state('verifyPhone', {
      url: "/verifyPhone",
      templateUrl: "client/www/views/verifyPhone.html",
      controller: "SMSVerificationController",
      resolve: {
        "currentUser": function ($meteor) {
          return $meteor.requireUser();
        }
      }
    });
    $locationProvider.html5Mode(true);
});

之后,您需要捕获requireUser promise错误,并将用户重定向到您的404页面:

app.run(function ($rootScope, $state) {
  $rootScope.$on('$stateChangeError', function (event, toState, toParams, fromState, fromParams, error) {
    if (error === 'AUTH_REQUIRED') $state.go('404');
  });
});