Skip to content

Instantly share code, notes, and snippets.

@bartholomej
Last active November 3, 2020 22:49
Show Gist options
  • Save bartholomej/c09478a1d462c9d9827c48184363e160 to your computer and use it in GitHub Desktop.
Save bartholomej/c09478a1d462c9d9827c48184363e160 to your computer and use it in GitHub Desktop.
Feature Guard Angular
const routes: Routes = [
{
path: 'en',
children: allRoutes,
canActivate: [FeaturesGuard],
data: { feature: 'i18n' } as FeaturesGuardModel
}
]
export const environment: Environment = {
features: {
events: false,
i18n: true,
groups: true
}
};
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, UrlTree } from '@angular/router';
import { environment } from '../../../environments/environment';
import { Features } from '../../../environments/environment.interface';
export interface FeaturesGuardModel {
feature: Feature;
}
type Feature = keyof Features;
@Injectable()
export class FeaturesGuard implements CanActivate {
constructor(private router: Router) {}
public canActivate(route: ActivatedRouteSnapshot): boolean | UrlTree {
const data: Feature = route.data.feature;
if (environment.features[data] === true) {
return true;
} else {
return this.router.parseUrl('/');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment