spring 如何从Angular表单中修剪值?

oyt4ldly  于 2023-08-02  发布在  Spring
关注(0)|答案(4)|浏览(127)

我有一个Angular表单,有两个输入,用户名和密码,当用户提交表单时,值会通过POST发送到Sping Boot REST控制器。我想在数据被发送到控制器之前修剪数据,但我找不到怎么做。
这是我的form-component.html:

<form  #loginForm="ngForm" (ngSubmit)="onSubmit()" name="loginForm">
        <input required ngModel [(ngModel)]="user.username" name="loginUsername" #loginUsername="ngModel" type="text" placeholder="Username">
        <div class="alert alert-danger" role="alert" *ngIf="loginUsername.invalid && (loginUsername.dirty || loginUsername.touched)">Username not inserted</div>
        <input required ngModel [(ngModel)]="user.password" name="loginPassword" #loginPassword="ngModel" type="text" placeholder="Password">
        <div class="alert alert-danger" role="alert" *ngIf="loginPassword.invalid && (loginPassword.dirty || loginPassword.touched)">Password not inserted</div>
        <button class="btn btn-primary" type="submit">Login</button>
    </form>

字符串
这是我的form-component.ts:

export class LoginFormComponent implements OnInit{

  user: User;

  constructor(private route: ActivatedRoute, 
    private router: Router, 
      private login: LoginService){
    this.user = new User();
  };

  ngOnInit(): void { };

  onSubmit() {
    this.login.send(this.user).subscribe(result => this.router.navigate(['/http://localhost:8080/login']));
  }

}


这是我的用户。ts:

export class User {

    username: string;
    password: string;

    constructor(){
        this.username = "";
        this.password = "";
    }
    
}


这是我的登录服务。ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { User } from '../classes/user';

@Injectable({
  providedIn: 'root'
})
export class LoginService {

  private loginUrl: string;

  constructor(private http: HttpClient) {
    this.loginUrl = 'http://localhost:8080/login';
   }

   public send(user: User) {
    return this.http.post<User>(this.loginUrl, user);
  }
}


这是我的Spring REST控制器:

@EnableDiscoveryClient
@SpringBootApplication
@RestController
@RequestMapping
@CrossOrigin(origins = "http://localhost:4200")
public class ApiGatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(ApiGatewayApplication.class, args);
    }

    @PostMapping("/login")
    public void postUser(@RequestBody User user) {
        System.out.println("Username:" + user.getUsername());
        System.out.println("Password:" + user.getPassword());
    }
}

dffbzjpn

dffbzjpn1#

你可以使用响应式表单来处理你的表单,它更容易处理表单。
它看起来像这样:
form-component.html:

<form  [formGroup]="loginForm" (ngSubmit)="onSubmit()" name="loginForm">
        <input required name="loginUsername" type="text" placeholder="Username" formControlName="username">
        <div class="alert alert-danger" role="alert" *ngIf="!formGroup.get('username').valid formGroup.get('username').touched)">Username not inserted</div>
        <input required name="loginPassword" type="text" placeholder="Password" formControlName="password">
        <div class="alert alert-danger" role="alert" *ngIf="!formGroup.get('password').valid formGroup.get('password').touched)">Password not inserted</div>
        <button class="btn btn-primary" type="submit">Login</button>
    </form>

字符串
form-component.ts:

import { FormGroup, FormControl } from '@angular/forms';
        export class LoginFormComponent implements OnInit{
        
          user: User;
loginForm = new FormGroup({
    username: new FormControl('', [TrimFormControl]),
    password: new FormControl('', [TrimFormControl]),
  });
        
          constructor(private route: ActivatedRoute, 
            private router: Router, 
              private login: LoginService){
            this.user = new User();
          };
        
          ngOnInit(): void { };
        
          onSubmit() {
            this.login.send(this.loginForm. getRawValue()).subscribe(result => this.router.navigate(['/http://localhost:8080/login']));
          }
        
        }


然后,您可以创建一个自定义验证器,自动修剪您的输入。
自定义验证器:

export class TrimFormControl extends FormControl {
    private _value!: string | null;

    get value(): string | null {
        return this._value;
    }

    set value(value: string | null) {
        this._value = value ? value.trim() : value;
    }
}


你把它放在数组中,在上面的表单组创建。在angular中使用响应式表单也是一个很好的实践,它更容易让你在表单中处理验证,并且使用相同的表单来创建和更新也非常有用。(您可以在创建表单组时填充输入,空字符串表示输入为空)。

js81xvg6

js81xvg62#

onSubmit() {
 this.user.userName = this.user.username.trim();
 this.user.password = this.user.passWord.trim();
 this.login.send(this.user).subscribe(result => 
 this.router.navigate(['/http://localhost:8080/login']));
}

字符串

gcxthw6b

gcxthw6b3#

或通过提交函数中的循环

onSubmit() {
    const formValues = Object.values(this.loginForm.value)
      .map((val: unknown) => val as string)
      .map((val: string) => val.trim());

    this.login.send(formValues).subscribe(...);
}

字符串

yrdbyhpb

yrdbyhpb4#

我做了一个自定义的表单验证器,它总是返回null(无错误)。在验证器中,我为输入设置值。

import { AbstractControl, ValidationErrors } from '@angular/forms';

export const trimValidator = (control: AbstractControl): ValidationErrors | null => {
    const value = control.value;

    if (!value || value === '') return null;

    if (value.startsWith(' ') || value.endsWith(' ')) {
        control.setValue(control.value?.trim(), { emitEvent: false, onlySelf: true });
    }

    return null;
};

字符串

相关问题