Skip to content

Instantly share code, notes, and snippets.

@amcdnl
Created March 8, 2018 17:37
Show Gist options
  • Save amcdnl/3f1eae45c4f9f713386f9b3838e53d72 to your computer and use it in GitHub Desktop.
Save amcdnl/3f1eae45c4f9f713386f9b3838e53d72 to your computer and use it in GitHub Desktop.
ngOnInit() {
this.filteredRoutes$ = from(this.routes).pipe(
concatMap((route) => {
// handle if nothing is in canActivate
if (!route.canActivate || !route.canActivate.length) {
// create an object that has the route and result for filtering
return of({ route, result: true });
}
return from(route.canActivate).pipe(
// execute the guard
switchMap(guard => {
const instance = this.injector.get(guard);
const result = instance.canActivate();
if (result instanceof Observable) {
return result;
} else {
return of(result);
}
}
),
// aggregate the guard results for the route
toArray(),
// ensure all results are true
map(results => results.every(r => r)),
// create an object that has the route and result for filtering
map(result => ({ route, result })));
}),
// filter out the invalid guards
filter(routeCanActivateResult => routeCanActivateResult.result),
// return just the route
map(routeCanActivateResult => routeCanActivateResult.route),
// turn it back into an array
toArray()
);
}
@Martin-Andersen
Copy link

I hope I one learn to write code like that, right know I am struggling reading it. I have been writing procedural code for 25 years

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment