简体   繁体   中英

Type 'Promise<boolean | void>' is not assignable to type 'boolean'

I cannot understand why it's saying I can't assign the return of a promise to a boolean type. Any other way I have tried this tells me I can't assign a void to type boolean. Not sure what to do from here

I am trying to assign the output of checkJWT to the resolution of a promise. It logically makes sense to me that I could do this, but typescript doesn't like it.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';


import { NotificationService } from '../index';
import { UserInterface } from '../../../models/index';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  constructor( 
    private notificationService: NotificationService,
    private httpClient: HttpClient
   ) { }

  checkJWT(role):boolean {
    let canVisit: boolean = this.httpClient.get(window.location.protocol + '//' + window.location.hostname + ':3000/authenticate')
    .toPromise()
    .then(
      (user: UserInterface) => { 
        return role === user.role;
    }
    ) .catch((err) => { this.notificationService })
    return canVisit;
  }

Try This

checkJWT(role):Promise<boolean>{
    let canVisit: Promise<boolean>= <Promise<boolean>>this.httpClient.get(window.location.protocol + '//' + window.location.hostname + ':3000/authenticate')
    .toPromise()
    .then(
      (user: UserInterface) => { 
        return role === user.role;
    }
    ) .catch((err) => { this.notificationService })
    return canVisit;
  }

Since this.httpClient.get().toPromise() is returning a Promise Object

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