Angular 2 - canActivate内部的服务调用

时间:2017-05-09 05:43:19

标签: angular

使用警卫,我尝试访问服务

但我无法在canActivate中返回一个承诺(具有我无法更改的特殊签名)

我的autService返回一个promise,因为它是asynchrone

我怎样才能实现类似的目标:

@Injectable()
export class AuthGuardService implements CanActivate {
    constructor(private authService: AuthService) {}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        let url: string = state.url;

        this.authService.canAccessUrl(url)
        .then( (answer:boolean) => {return answer;} );

    }
}

感谢

1 个答案:

答案 0 :(得分:2)

您只需更改 canActivate

的签名即可
@Injectable()
export class AuthGuardService implements CanActivate {
constructor(private authService: AuthService) {}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
    let url: string = state.url;

    this.authService.canAccessUrl(url)
    .then( (answer:boolean) => {return answer;} );

   }
}

请检查https://angular.io/docs/ts/latest/api/router/index/CanActivate-interface.html