简体   繁体   中英

Angular CanActivated: canActivated return toPromise

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().

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM