微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从 FormGroup 获取数据并添加最旧的假数据

如何解决如何从 FormGroup 获取数据并添加最旧的假数据

我正在做我的第一个 Angular Reactive Form 项目,我有 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.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,[{email:"",password:""}]]

解决方法

在 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);
  }

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

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;
  }
  
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。