简体   繁体   English

angular - 如何创建一个 canActivate 保护以仅允许来自另一个组件的重定向?

[英]angular - How to create a canActivate guard to only allow redirects from another component?

I have a component that I wish to allow it's access only in case of a redirect from another component.我有一个组件,我希望仅在从另一个组件重定向的情况下才允许它访问。
So if I put the url in the browser it wouldn't allow me to access it but, if I redirect to it from another specific component like this it will be allowed:因此,如果我将 url 放在浏览器中,它将不允许我访问它,但是,如果我从另一个像这样的特定组件重定向到它,它将被允许:

this.router.navigate(['/main/myLockedComponent']);

I thought of adding a canActivate guard similar to an authGuard like so:我想添加一个类似于 authGuard 的 canActivate 守卫,如下所示:

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ValidationGuardService implements CanActivate{

  constructor() { }
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean  {
    console.log(route);
    console.log(state);
    return true;
  }
}

but by printing state and route I can't find the information I need like whether this component was redirected to internally from an angular component (and better yet from which component) or not .但是通过打印 state 和路由,我找不到我需要的信息,例如该组件是否从 angular 组件内部重定向到内部(更好的是从哪个组件)

Edit: I am using angular 11.编辑:我正在使用 angular 11。

If you want to check if you are redirected from a route like this www.testsite.com/main/profile , you could write a condition inside your guard as如果你想检查你是否从这样的路线重定向www.testsite.com/main/profile ,你可以在你的警卫内写一个条件为

import { Injectable } from '@angular/core';
import { CanActivate, Router} from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ValidationGuardService implements CanActivate{

  constructor(private router : Router) { }
  canActivate(): boolean  {

    let currentUrl = this.router.url;
    let isFromProfile = currentUrl.indexOf('/profile') == -1 ? false : true;
    console.log(currentUrl);
    if(isFromProfile)
       return true;
    else 
       return false;
    }
}

You could also use the below method to check whether the last part of the url is the one we are expecting:您还可以使用以下方法检查 url 的最后一部分是否是我们所期望的:

let isFromProfile = this.router.url.split('/').pop() === 'profile';

Hope this answered your question:-)希望这回答了你的问题:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM