Angular 8多条件判断替换三元运算符后Promise调用报错问题
问题分析与解决方案
你遇到的问题根源很明确:新方法里错误地把字符串类型的type直接赋值给了promise变量,这当然不是Promise类型,自然没法调用.then()方法啦!
先拆解下你的错误点:
public disapprove = (type: 'Reset' | 'Reject' | 'Approve' ) => { if ( type === 'Reset') { this.service.reset(this.id, this.type, this.message); } else if (type === 'Reject') { this.service.reject(this.id, this.type, this.message); } else if (type === 'Approve') { this.service.approve(this.id, this.type, this.message); } // 这里完全错了!type是字符串,不是Promise! const promise = type; promise.then(() => { ... }); }
原来的三元运算符是直接把service返回的Promise赋值给promise变量,而新方法里你只是调用了service的方法,却没把返回的Promise存下来,反而把type字符串赋值给了promise,这就导致了类型不匹配的问题。
修正方案1:正确存储Promise变量
我们可以先声明一个Promise类型的变量,然后在每个分支里给它赋值,之后再统一调用.then():
public disapprove = (type: 'Reset' | 'Reject' | 'Approve') => { let promise: Promise<void>; // 先声明Promise类型的变量 if (type === 'Reset') { promise = this.service.reset(this.id, this.type, this.message); } else if (type === 'Reject') { promise = this.service.reject(this.id, this.type, this.message); } else { promise = this.service.approve(this.id, this.type, this.message); } promise.then(() => { this.messageService.add(`Successfully ${type}.`, 'info'); this.navigateToApprovalList(); }); }
修正方案2:用对象映射让代码更简洁(推荐)
如果后续还有更多类型需要扩展,用对象映射的方式会更清爽,可读性也更高:
public disapprove = (type: 'Reset' | 'Reject' | 'Approve') => { // 定义type对应的service方法映射 const actionMap = { Reset: () => this.service.reset(this.id, this.type, this.message), Reject: () => this.service.reject(this.id, this.type, this.message), Approve: () => this.service.approve(this.id, this.type, this.message) }; // 获取对应的方法并调用,得到Promise const promise = actionMap[type](); promise.then(() => { this.messageService.add(`Successfully ${type}.`, 'info'); this.navigateToApprovalList(); }); }
另外,建议你加上错误处理逻辑,避免Promise失败时没有反馈:
promise.then(() => { this.messageService.add(`Successfully ${type}.`, 'info'); this.navigateToApprovalList(); }).catch(error => { this.messageService.add(`Failed to ${type}: ${error.message}`, 'error'); });
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

