使用location.path(哈希)进行验证

时间:2018-08-28 17:47:59

标签: javascript angularjs

我正在使用ng-route,我想要做的是在将客户发送到一页或显示警告消息之前进行验证。

每个例子,让我们假设我有两种类型的客户:

$scope.idCostumer = 15;

var costumerGood = 1;
var costumerBad = 2;

我的想法是验证类似这样的内容:

$scope.sendTo = function(){
   if(costumerGood === 1){
      location.path(hash).search({id: $scope.idCostumer});
   }
   else{
      alert("You can't access here);
   }
}

我知道正确的路径将是:

$scope.sendTo = function(hash){
      location.path(hash).search({id: $scope.idCostumer});
}

但是验证没有用。控制台错误向我显示的是location.path is not a function。有验证的方法吗?

我正在使用Javascript和AngularJs。

先感谢

1 个答案:

答案 0 :(得分:-1)

我不确定您是否很好地理解了您的问题,但是如果您尝试管理对页面/组件的访问,我建议使用Route Guards机制:https://angular.io/guide/router#milestone-5-route-guards

您将能够在后卫中实施您的想法。 警卫队的例子:

import { Injectable }       from '@angular/core';
import {
  CanActivate, Router,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  CanActivateChild,
  NavigationExtras
}                           from '@angular/router';
import { AuthService }      from './auth.service';

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    let url: string = state.url;

    return this.checkPermissions(url);
  }

  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    return this.canActivate(route, state);
  }

  checkPermissions(url: string): boolean {
    if (this.authService.isLoggedIn) { return true; }

    // Store the attempted URL for redirecting
    this.authService.redirectUrl = url;

    // Create a dummy session id
    let sessionId = 123456789;

    // Set our navigation extras object
    // that contains our global query params and fragment
    let navigationExtras: NavigationExtras = {
      queryParams: { 'session_id': sessionId },
      fragment: 'anchor'
    };

    // Navigate to the login page with extras
    this.router.navigate(['/login'], navigationExtras);
    return false;
  }
}

如果您可以指出所使用的Angular版本,将会很有帮助。