Angular17中SMS验证码自动填充报错,求解决方法
修复Angular 17中WebOTP验证码自动填充的TypeScript错误
错误1:otp不是CredentialRequestOptions的已知属性
TypeScript默认DOM类型定义未包含WebOTP API的otp配置项,需手动扩展全局类型:
在组件文件顶部或单独的类型声明文件(如src/types/web-otp.d.ts)中添加以下代码:
declare global { interface CredentialRequestOptions { otp?: { transport: ('sms' | 'voice')[]; }; } } export {};
通过声明合并扩展CredentialRequestOptions接口,补上WebOTP所需的otp属性。
错误2:Credential类型不存在code属性
WebOTP返回的实际是OtpCredential类型(继承自Credential),该类型包含code字段。需将获取到的凭证做类型断言:
修改组件中获取凭证的代码:
const credential = await navigator.credentials.get({ otp: { transport: ['sms'] }, signal: abortController.signal }) as OtpCredential; // 添加类型断言 if (credential) { this.otpCode = credential.code; // 可正常访问code属性 }
若TypeScript不识别OtpCredential,同样扩展全局类型:
declare global { interface OtpCredential extends Credential { code: string; } } export {};
完整修改后的组件代码示例
import { Component, OnInit, OnDestroy } from '@angular/core'; import { CommonModule } from '@angular/common'; declare global { interface CredentialRequestOptions { otp?: { transport: ('sms' | 'voice')[]; }; } interface OtpCredential extends Credential { code: string; } } @Component({ selector: 'app-otp', standalone: true, imports: [CommonModule], template: ` <input type="text" [(ngModel)]="otpCode" placeholder="验证码" /> ` }) export class OtpComponent implements OnInit, OnDestroy { otpCode = ''; private abortController = new AbortController(); ngOnInit(): void { this.requestOtp(); } async requestOtp() { try { const credential = await navigator.credentials.get({ otp: { transport: ['sms'] }, signal: this.abortController.signal }) as OtpCredential; if (credential) { this.otpCode = credential.code; } } catch (err) { console.error('验证码获取失败:', err); } } ngOnDestroy(): void { this.abortController.abort(); } }
额外注意事项
- 确保
tsconfig.json的lib数组包含"dom",启用DOM类型检查 - WebOTP仅在HTTPS环境生效(本地开发可使用
localhost) - 短信格式需符合规范:末尾必须包含
@你的站点域名 #验证码(如@example.com #123456)
内容的提问来源于stack exchange,提问作者Ermak
相关产品推荐
相关产品推荐

