问题描述
我正在做我的第一个 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;
}
}