Malikiah
Malikiah

Reputation: 149

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

Upvotes: 1

Views: 16591

Answers (1)

manish kumar
manish kumar

Reputation: 4700

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

Upvotes: 3

Related Questions