类型‘Promise<string>’不可赋值给‘string’及悬停显示服务响应咨询
解决方法
1. 修正类型不匹配问题
你遇到的错误是因为checkSaldo返回的是Promise<string>类型,而toolTip定义的是string类型,直接赋值会导致类型不兼容。需要等待Promise执行完成后,再把结果赋值给toolTip,只需把setTimeout的回调改成异步函数,用await获取Promise的结果即可:
toolTip: string; handle: any; async mouseover(params) { this.handle = setTimeout(async () => { this.toolTip = await this.checkSaldo(10, 'FRA'); this.show = true; }, 4000); } checkSaldo(amount: any, currencyCode: any): Promise<string> { return new Promise((resolve) => { this.restService.getByParam('recalculatedSaldo', { amount: amount, currency: currencyCode }).subscribe(response => { resolve(response.payload); }); }); }
2. 优化Promise转换(可选)
Angular的Observable可以用RxJS的工具直接转成Promise,不用手动封装,代码更简洁:
import { firstValueFrom } from 'rxjs'; // ... checkSaldo(amount: any, currencyCode: any): Promise<string> { const request$ = this.restService.getByParam('recalculatedSaldo', { amount, currency: currencyCode }); return firstValueFrom(request$).then(res => res.payload); }
3. 补充鼠标移出清理逻辑(优化)
如果用户快速移入移出元素,定时器可能仍会触发tooltip,建议添加mouseout事件清除定时器:
mouseout() { clearTimeout(this.handle); this.show = false; this.toolTip = ''; }
内容的提问来源于stack exchange,提问作者None
相关产品推荐
相关产品推荐

