ng 手机验证码验证/发送(含倒计时)
ng 的手机号码进行验证:
1.在对应的ts文件中,先声明一个变量
private mobile: string
private btnCaptchaText: string = '发送验证码'
private timeLeft: number = 0
2.在对应的触发事件中写入需要的事件代码
if (!/^1[3456789]{1}\d{9}$/.test(this.mobile)) {
this.countDown(60, (timeLeft) => {
this.btnCaptchaText = `${this.timeLeft}s`
},
() => {
this.btnCaptchaText = '获取验证码'
})
return
}
this.playerService.getUserCode(this.mobile).subscribe(
res => {
this.countDown(60, (timeLeft) => {
this.btnCaptchaText = `${this.timeLeft}s`
},
() => {
this.btnCaptchaText = '获取验证码'
})
console.log(res)
}
)
}
countDown(times: number, onCount, onComplete) {
this.timeLeft = times
let timer = setInterval(() => {
if (this.timeLeft <= 0) {
clearInterval(timer)
onComplete()
} else {
this.timeLeft--
onCount(this.timeLeft)
}
}, 1000)
}
解析:getUserCode 就是在服务中数据传输中定义的函数
=> xxx.service.ts中
userCodeUrl:string = "http://192.168.1.87:8081/api/captcha/bindMobile";
getUserCode(mobile: string):Observable<any>{
return this.http.post(this.userCodeUrl, {mobile}, this.httpOptions)
}
2.对应的html中
<span><button (click)="sendcode()" [disabled]="timeLeft > 0">{{btnCaptchaText}}</button></span>