Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
Angular 2 How to Apply Multiple Guards with Or-Relationship on the Same Path

My application allows access to contents based on user roles. I wrote a Router Guard for each role. Some contents allow access for role1 or role2 or role3. How should I write that canActivate declaration in the feature-routing.module.ts file? As I understand, if I write

canActivate:[Role1Guard, Role2Guard, Role3Guard]

The access will be denied if any of the guards returns false. But in my case, I should allow access if any of the guards returns true. How to do it? Many thanks in advance!

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

What we can do in this case is create a Master Guard which will trigger the application guards as per our requirement.

Checkout this answer to understand the approach.

Assuming you have gone through it above link, the approach in this case could be as simple as modifying the data property in Route class.

Something like this -

{
    path: "view2",
    component: View2Component,
    //attach master guard here
    canActivate: [MasterGuard],
    //this is the data object which will be used by 
    //masteer guard to execute guard1, guard 2, guard 3 & guard 4
    data: {
        trigger: {
            operator: "OR",
            guards: [
                GUARDS.GUARD1,
                GUARDS.GUARD2,
                GUARDS.GUARD3,
                GUARDS.GUARD4
            ]
        }
    }
}

And then use operator flag to fire all guards accordingly.

I hope this helps :)

about 4 years ago · Santiago Trujillo Report

0

You could write OrGuard, something like:

class OrGuard() {
  guards: any[];
  constructor(...guards) { this.guards = guards }

  canActivate() {
    return this.guards.some(Boolean);
  }
}

and use it like this:

canActivate:[new OrGuard(Role1Guard, Role2Guard, Role3Guard)]

...just an idea, actual implementation might be different, I didn't try (;

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!