3

Using guards, I try to access a service

but I cant return a promise in canActivate (which has particular signature that I cannot change)

my autService returns a promise since it is asynchrone

how can I achieve something similar :

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

    }
}

thanks

ninja
  • 463
  • 1
  • 7
  • 14
  • 1
    You know canActivate can return `Observable|Promise|boolean`. What do you mean by "signature that I cannot change" ? – eko May 09 '17 at 05:48
  • take a look at this answer by me hope this helps http://stackoverflow.com/questions/41463343/get-the-value-returned-by-canactivate-method-in-angular2-route-in-a-component/41467816#41467816 – Rahul Singh May 09 '17 at 05:54
  • ok , why dont they talk about this in the doc.... – ninja May 09 '17 at 06:04
  • @Rahul Singh it does not answer the question – ninja May 09 '17 at 06:05
  • @echonax do you have any example, cos so far the only one I found use :boolean – ninja May 09 '17 at 06:17
  • @ninja I don't know where you are looking for examples.. It's in the official documentation: https://angular.io/docs/ts/latest/api/router/index/CanActivate-interface.html – eko May 09 '17 at 06:18

1 Answers1

3

You just need to change the signature of 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;} );

   }
}

Please check https://angular.io/docs/ts/latest/api/router/index/CanActivate-interface.html

Jayakrishnan
  • 4,232
  • 2
  • 23
  • 35