angularangular-routingangular-routerangular-router-guardscanactivate

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:

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

I thought of adding a canActivate guard similar to an authGuard like so:

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.

Edit: I am using angular 11.


Solution

  • 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

    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 :

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

    Hope this answered your question :-)