相关文章推荐
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I am trying to create a guard in order to validate if user is allowed to navigate to a route based on busines logic.

But I am getting The return type of an async function or method must be the global Promise type.ts

async canActivate(
  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
  const idCliente = +next.paramMap.get('id');
  const usuario = await this.authService.getUserSubject().pipe(first()).toPromise()
  const cliente = await this.clienteService.obtenerCliente(idCliente).pipe(first()).toPromise()
  return new Promise<boolean>((resolve, reject) => {
    resolve(usuario.empresaId === cliente.empresaId)
                That's correct, an async function can't return an observable, boolean or URL tree - it always returns a promise.
– jonrsharpe
                Aug 22, 2020 at 20:31

Since the return type is Promise you might want to modify the return type:

 async canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {

It would be more advisable to use Observable (rather than converting the results from both getUserSubject and obtenerCliente into Promises) as demonstrated below:

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
  const idCliente = +next.paramMap.get('id');
  return combineLatest(
    this.authService.getUserSubject(),
    this.clienteService.obtenerCliente(idCliente)
    .pipe(
      first(),
      map(([usuario, cliente]) => usuario.empresaId === cliente.empresaId)
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.

 
推荐文章