即使Observable返回true,Angular CanActivate也无法刷新浏览器

时间:2018-11-14 09:23:00

标签: angular typescript angular2-routing

我们为CanActivate提供了一个路由防护,当您在站点上的链接之间单击时,它可以正常工作,但是当我们完全刷新浏览器时(即,它重定向到主页,其行为与{{1 }}返回false)。

这是我的警卫

CanActivate

这是我的路由器配置:-

@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$;
    }
}

这很重要,请使用path: 'security/security-example', component: SecurityExampleComponent, canActivate: [PermissionCheckGuard], data: { permissionTag: 'Site_Permission_1' } 函数

hasPermission

我看不到我在做什么错,警卫返回一个可观察到的消息,控制台日志始终返回 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); }) } 。这是angular的问题,还是我的代码有错误?

1 个答案:

答案 0 :(得分:0)

我猜想在您得到回应之前,它已经解决了。在此处尝试使用subject

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();
}