angularobservableguard

Angular Guard Function Return Boolean Observable


I need to have a route guard function read in some data from the localStorage, but because of how angular executes (from what I have read) it doesn't wait to read in the values before completing the guard function. This is why an observable is needed, which actually waits to process the data.

The problem is that all examples have a service and other extra things. I just need to read in the localStorage value. Nothing fancy at all. This will either return a observable boolean value or a UrlTree.

export const isValuePresentGuard: CanActivateFn = (): Observable<boolean> | UrlTree => {
    const fromLocalStorage = localStorage.getItem('data');
    
    if(fromLocalStorage) {
        return true;
    }

    return inject(Router).createUrlTree(['/another-page']);
};

I might be over thinking this. Any thoughts?


Solution

  • CanActivateFn is actually defined as

    export type CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) =>
        Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree;
    

    You can return boolean|UrlTree without any problem.