Home > Blockchain >  Angular CanActivated: canActivated return toPromise
Angular CanActivated: canActivated return toPromise

Time:11-14

I want to return a promise function in Angular canActivate function. How to convert the codes below so that it can return promise. I know I can use toPromise() to make it works but since toPromise is marked as deprecated. How to use lastValueFrom() so that it can produce the same result.

canActivate(
    _route: ActivatedRouteSnapshot,
    _state: RouterStateSnapshot
  ):
    | Observable<boolean | UrlTree>
    | Promise<boolean | UrlTree>
    | boolean
    | UrlTree {
    const token: string | null = this.cookieService.getCookie('webguard-token')
    const tokenValidated = token === null ? '' : token

    return this.webguardService
      .validateUserHasPermission('IsModerator')
      .toPromise()
      .then(async () => {
        return await this.webguardService
          .validateToken(tokenValidated)
          .toPromise()
          .then(() => {
            return true
          })
          .catch(() => {
            window.location.replace('/webguard/login/')
            return false
          })
      })
      .catch(() => {
        window.location.replace('/webguard/login/')
        return false
      })
  }

I tried to use lastValueFrom() but canActivate() is not an async function. I don't know how to use lastValueFrom() in canActvate().

CodePudding user response:

lastValueFrom() is a function that wraps an Observable:

return lastValueFrom(this.webguardService.validateUserHasPermission('IsModerator'))
  .then(async () => await 
    lastValueFrom(this.webguardService.validateToken(tokenValidated))
      .then(...)

Btw, you could do the same with just RxJS Observable and chain mergeMap(), catchError() and similar operators.

  • Related