【问题标题】:Type 'Promise<boolean | void>' is not assignable to type 'boolean'输入'承诺<boolean | void>' 不可分配给类型 'boolean'
【发布时间】:2019-02-11 05:52:44
【问题描述】:

我不明白为什么它说我不能将承诺的返回分配给布尔类型。我尝试过的任何其他方式都告诉我,我不能分配一个 void 来键入布尔值。不知道从这里做什么

我正在尝试将 checkJWT 的输出分配给承诺的解决方案。我可以这样做从逻辑上讲是有道理的,但 typescript 不喜欢它。

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

【问题讨论】:

  • 因为这个checkJWT(role):boolean应该是checkJWT(role):Promise&lt;boolean&gt;,如果你想直接返回数据,使用async await
  • 在这里您将 caVisit 声明为布尔变量,但 get 方法返回 Promise 这就是您收到错误的原因

标签: angular typescript


【解决方案1】:

试试这个

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

因为this.httpClient.get().toPromise() 正在返回一个Promise 对象

【讨论】:

  • 这是我这样做时返回的结果:“类型 'Promise' 不可分配给类型 'Promise'。”
  • http.client 类型转换为>
  • @Nymad 也接受作为帮助他人的答案。
  • 这是因为,你没有从catch 返回任何东西。类型转换只会隐藏您可能遇到的问题。 @Nymad
猜你喜欢
  • 2023-01-18
  • 2017-06-29
  • 1970-01-01
  • 2021-08-19
  • 2016-06-24
  • 2021-06-07
  • 1970-01-01
  • 1970-01-01
  • 2020-08-29
相关资源
最近更新 更多