2

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.

wazzup
  • 39
  • 7

1 Answers1

1

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 :-)

Arun s
  • 869
  • 9
  • 19
  • I have updated the answer . i wrongly added private router : Router inside canActivate earlier. Now added in constructor. – Arun s Feb 22 '21 at 13:22
  • Thank you for the answer, but canActivate doesn't take a Router parameter and it throws an error "Property 'canActivate' in type 'ValidationGuardService' is not assignable to the same property in base type 'CanActivate'. Type '(router: Router) => boolean' is not assignable to type '(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => boolean | UrlTree | Observable | Promise<...>'..." – wazzup Feb 22 '21 at 13:22
  • 1
    I have updated the answer . i wrongly added private router : Router inside canActivate earlier. Now added in constructor. – Arun s Feb 22 '21 at 13:23