如何从URL中获取令牌的值并将其分配给输入的值

时间:2019-02-16 08:02:48

标签: angular

当前它不使用令牌输入令牌的值,它只是在控制台中打印“”,因为我将令牌定义为 令牌:['']在表单构建器中。我应该如何定义它以使其取正确的值。 整个过程的最终目的是从mydomain.com/reset-password?token=2724a63c5ab6866ae385ea211cb1获取令牌的值 因此在这种情况下,应在隐藏令牌输入字段中更新2724a63c5ab6866ae385ea211cb1,以便可以在表单提交时将其发送到后端。

html(我在这里使用反应形式)

<form [formGroup]="resetPassword" (ngSubmit)="onSubmit()">
    <div id="tab-1" class="log-tab-content current">
      <div class="login-form">
        <div class="login-left">
            <input type="text" formControlName="password" name="password" placeholder="Enter New Password *"/>
            <div class="clearfix"></div>
        </div>
        <div class="login-right">
          <input type="text" formControlName="c_password" placeholder="Confirm Password *"/>
          <div class="clearfix"></div>
        </div>
        <input type="hidden" formControlName="token" name="token" value="2724a63c5ab6866ae385ea211cb1d3812696fe574a71817515e50038a0881aa1">
        <div class="clearfix"></div>
        <button type="submit" class="log-button log-button1">Reset Password</button>
      </div>
    </div>
 </form>

打字稿

 constructor(private formBuilder: FormBuilder, private auth: AuthService) { }

  ngOnInit() {
    this.resetPassword = this.formBuilder.group({
      password: ['', Validators.required],
      c_password: ['', Validators.required],
      token: ['']
    })
  }

  onSubmit() {
    this.submitted = true;
    if (this.resetPassword.invalid) {
      return;
  }
  const user = {
    password: this.resetPassword.controls.password.value,
    c_password: this.resetPassword.controls.c_password.value,
    token: this.resetPassword.controls.token.value
  };

  console.log(user);

  this.auth.resetPasswordToken(user).subscribe( (res: any) => {
    if(res) {
     console.log(res);
    }
  },(err)=> {
  if(err) {
    console.log(err);
  }
  });
}

1 个答案:

答案 0 :(得分:2)

已更新:

将ngModel绑定到您的输入[(ngModel)]="mytoken",如下所示。

<input type="hidden" formControlName="token" name="token" [(ngModel)]="mytoken" value="2724a63c5ab6866ae385ea211cb1d3812696fe574a71817515e50038a0881aa1">
        <div class="clearfix"></div>
        <button type="submit" class="log-button log-button1">Reset Password</button>
        </div>

然后在您的ts中初始化变量mytoken,并在您订阅后添加以下内容

  this.auth.resetPasswordToken(user).subscribe( (res: any) => {
    if(res) {
     console.log(res);
     this.mytoken = res; // depends on the response data. It could also be res.token
    }
  },(err)=> {
  if(err) {
    console.log(err);
  }
  });

如果您无法根据角度版本在ngModel字段上使用input,则可以使用setValue

  this.auth.resetPasswordToken(user).subscribe( (res: any) => {
    if(res) {
     console.log(res);
     this.resetPassword.controls['token'].setValue(res); // depends on the response data. It could also be res.token
    }
  },(err)=> {
  if(err) {
    console.log(err);
  }
  });