[英]Angular2/4 populate form after request
I am using the same form for both user adding and user editing.我对用户添加和用户编辑使用相同的表单。 If a user is logged in I know that I'm editing the form and if a user is not logged in I'm adding a new user.
如果用户已登录,我知道我正在编辑表单,如果用户未登录,我将添加新用户。
The problem I'm facing is that when user is logged in I have to query the backend API for user data to fill the form and because the GET
request is async
the form is already created before i get the data.我面临的问题是,当用户登录时,我必须查询后端 API 以获取用户数据以填写表单,并且因为
GET
请求是async
所以在我获取数据之前已经创建了表单。 Here is what I have:这是我所拥有的:
ngOnInit() {
let userData = null;
if (this.userService.userId) { // user is logged in, query for data
this.http.get('http://localhost/api/user/get/' + this.userService.userId)
.subscribe(
(data) => {
userData = data.json();
},
(error) => {
}
);
}
//init form
this.form = new FormGroup({
id: new FormControl(userData ? userData.id : ''),
name: new FormControl(userData ? userData.name : '', Validators.required)
});
}
One solution I thought of is to duplicate the form init in the get block after I get the data but this doesn't seem like a good solution, especially when the form init can have a lot of fields.我想到的一个解决方案是在获取数据后在 get 块中复制表单 init 但这似乎不是一个好的解决方案,尤其是当表单 init 可以有很多字段时。
What would be a clean solution for this case?对于这种情况,什么是干净的解决方案?
A clean solution to your problem would look like this -您的问题的干净解决方案如下所示 -
ngOnInit() {
let userData = null;
//init form
this.form = new FormGroup({
id: new FormControl(userData ? userData.id : ''),
name: new FormControl(userData ? userData.name : '', Validators.required)
});
if (this.userService.userId) { // user is logged in, query for data
this.http.get('http://localhost/api/user/get/' + this.userService.userId)
.subscribe(
(data) => {
userData = data.json();
this.form.patchValue({
id: userData.id,
name: userData.name
})
},
(error) => {
}
);
}
}
Notice here that the FormGroup
is initialized before the GET
request is sent.注意这里
FormGroup
是在发送GET
请求之前初始化的。 And later patchValue
is used to bind the new values to the formControlName
后来
patchValue
用于将新值绑定到formControlName
Hope this helps.希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.