首页 > 解决方案 > 如何从 FormGroup 获取数据并添加最旧的假数据

问题描述

我正在做我的第一个角度反应表单项目,我有 fakedata 作为服务中的用户数据和注册表单,我想获取表单值作为新的用户数据并将其添加到我的假数据中,这就是我所拥有的完毕

在 Sign-UpComponent.ts

export class SignUpComponent implements OnInit {
  
  SignUpForm: FormGroup;
  constructor( private fb:FormBuilder) {
    this.SignUpForm=this.fb.group({
      email:[ "" ,[Validators.required ,Validators.minLength(5), Validators.email , Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$")]],
      password:[ "" ,[Validators.required ,Validators.minLength(6)]] 
    }
  }  
  onSubmit(){
    let aaa=this.newUserData
    console.log(aaa);
  }  
  get newUserData(){ 
    const newUser:User[]=[{
      password:this.SignUpForm.controls.password.value,
      email : this.SignUpForm.controls.email.value,
    }]  
  return newUser;
  }

直到这里,console.log 将 newUser 的值打印为 [{email:"aaa@gmail.com",password:123456}]

然后我将 newUser 变量传递给用户服务,如下所示

export class UsersDataService {
  data:User[]=[{
    password:"123456",
    email:"bbb@gmail.com",
  }]

  newUser:User[]
  allUsers:User[]=[]


  getDataInfo(){
    this.allUsers=this.data.concat(this.newUser);
    return this.allUsers;
  }
  

  constructor(  SignUpComponent:SignUpComponent) {
    this.newUser= SignUpComponent.newUserData
   }
}

现在应该console.log (allUsers)[[{email:"bbb@gmail",password:123456}],[{email:"aaa@gmail",password:123456}]]

但它显示没有价值 [[{email:bbb@gmail,password:123456}],[{email:"",password:""}]]

标签: angular-servicesangular-forms

解决方案


在 SignupComponent 中,我将 newUser 数据发送给服务

  onSubmit(){
    this.newUserData()
  }  

  newUserData(){ 
    let newUser:User={
      password:this.SignUpForm.controls.password.value,
      email : this.SignUpForm.controls.email.value    }  
    this.UsersDataService.getNewUser(newUser);
  }

然后我将它推送到用户服务中的数据 []

export class UsersDataService {
  data:User[]=[{
    password:"123456",
    email:"aaa@gmail.com",
  }]
  
  constructor() {
  }


  getNewUser(newUser:User){
    this.data.push(newUser);
    
  }
  
  getDataInfo(){
    console.log(this.data);
    return this.data;
  }
  
}

推荐阅读