简体   繁体   中英

Angular CanActivate failing on browser refresh even though observable returns true

We have a routing guard for CanActivate that works fine when clicking between links on the site, but fails when we fully refresh the browser (ie it redirects to the home page, the same behaviour as if CanActivate returns false).

This is my guard

@Injectable()
export class PermissionCheckGuard implements CanActivate {
    constructor(private userPermissionService: UserPermissionService) { }

    canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot
    ): Observable<boolean> | Promise<boolean> | boolean {
        let permissionTag = route.data["permissionTag"] as string;

        let hasPermission$ = this.userPermissionService.hasPermission(null, SubjectType.Site, permissionTag, null);

        hasPermission$.subscribe(x => {
            console.log(x);
        });

        return hasPermission$;
    }
}

This is my router config:-

path: 'security/security-example', component: SecurityExampleComponent, canActivate: [PermissionCheckGuard], data: { permissionTag: 'Site_Permission_1' }

In case it matters this is the hasPermission function

 public hasPermission(userId: string, subjectType: SubjectType, permissionTag: string, subjectId: string): Observable<boolean> {

        if (userId == null) {
            userId = 'Current';
        }

        const url = this.apiUrlBuilder.create('Security', 'Users', userId, 'Permission', {
            permissionTag: permissionTag,
            subjectType: subjectType,
            subjectId: subjectId
        });

        return this.http.get(url)
            .map<Response, boolean>((response: Response) => {
                return <boolean>response.json();
            })
            .catch((error) => {
                return this.errorHandlingService.ToNotification(error, this);
            })
    }

I don't see what I'm doing wrong, the guard is returning an observable and the console log is always returning true . Is this an issue with angular or is there a mistake in my code?

I guess somehow it is resolved before you get response. Try using subject here.

import { Subject } from 'rxjs';

canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
    let permissionTag = route.data["permissionTag"] as string;

    let hasPermission$ = this.userPermissionService.hasPermission(null, SubjectType.Site, permissionTag, null);

 const subject: Subject<boolean> = new Subject();
    hasPermission$.subscribe(x => {
        console.log(x);
        subject.next(x);
    });

    return subject.asObservable();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM