phone code validation ng / transmission (including countdown)

ng phone number to verify:

   1. In the corresponding ts files, declare a variable

  private mobile: string
  private btnCaptchaText: string = 'transmission codes'
   private timeLeft: number = 0
 
 2. Write in the corresponding event code needs to trigger events
  
   if (!/^1[3456789]{1}\d{9}$/.test(this.mobile)) {
          this.countDown(60, (timeLeft) => {
          this.btnCaptchaText = `${this.timeLeft}s`
         },
          () => {
            this.btnCaptchaText = 'Get codes'
         })
          return
      }  
 
      this.playerService.getUserCode(this.mobile).subscribe(
        res => {
          this.countDown(60, (timeLeft) => {
          this.btnCaptchaText = `${this.timeLeft}s`
          },
          () => {
            this.btnCaptchaText = 'Get codes'
          })
          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)
  }
 
Analysis: getUserCode function is defined in the data transmission services
  => Xxx.service.ts in
 
   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. in the corresponding html
 <span><button (click)="sendcode()" [disabled]="timeLeft > 0">{{btnCaptchaText}}</button></span>
 

Guess you like

Origin www.cnblogs.com/rockyjs/p/11896904.html
Recommended