Angular 从某个函数获取数据,并将其用作formModel参数的默认值
在我的角分量中,我有Angular 从某个函数获取数据,并将其用作formModel参数的默认值,angular,forms,model,components,Angular,Forms,Model,Components,在我的角分量中,我有 import { NgForm } from '@angular/forms'; export class ProfileComponent implements OnInit { userProfile; formModel={ FirstName:"", LastName:"" } 在ngOnInit中,我有一个获取数据的函数 ngOnInit() { this.service.getUserProfile().subscribe(
import { NgForm } from '@angular/forms';
export class ProfileComponent implements OnInit {
userProfile;
formModel={
FirstName:"",
LastName:""
}
在ngOnInit中,我有一个获取数据的函数
ngOnInit() {
this.service.getUserProfile().subscribe(
res => {
this.userProfile = res;
我想要的是使用该数据作为formModel的默认值。可能吗?怎么做
ngOnInit() {
this.service.getUserProfile().subscribe(
res => {
this.userProfile = res;
在您的ngOnInit中,您已将响应分配给userProfile。现在您可以在模板上显示这些数据。
所以有三种方法可以让你完成这个特殊的过程:
选项1:
使用可以打开和关闭的标志
ngOnInit() {
this.formReadyFlag = false;
this.service.getUserProfile().subscribe(
res => {
this.userProfile = res;
this.formReadyFlag = true;
})
}
相应地,在html中,您将仅在从服务器检索响应后呈现表单
component.html
<input [(formModel)]="userProfile?.name" *ngIf="formReadyFlag"/>
<input [(formModel)]="(userProfile | async)?.name"/>
与前面的选项相比,此选项不那么繁琐
选项3:
利用observables和async pipe,这样您就可以编写更少的样板代码,并且一切都可以顺利进行。如果您想对响应执行某些操作,则不能使用此方法
组件。ts
this.userProfile$ = Observable<any> | Subscription<any>;// Depends on the response type of the service method.
ngOnInit() {
this.userProfile$ = this.service.getUserProfile();
}
this.userProfile$=Observable | Subscription;//取决于服务方法的响应类型。
恩戈尼尼特(){
this.userProfile$=this.service.getUserProfile();
}
component.html
<input [(formModel)]="userProfile?.name" *ngIf="formReadyFlag"/>
<input [(formModel)]="(userProfile | async)?.name"/>
为什么不呢?只需像处理this.userProfile=res一样分配订阅中的数据。那么在哪里分配formModel的默认值???userProfile与模板不同,formValue是响应的st。如果FormModel属性绑定到ts中的FormModel对象,则可以直接赋值。我生成的FormModel为空。同时,我调用getUserProfile,从中接收该表单的数据。您可以编写解决方案吗?如何将该数据作为formModel的默认值传输?if(res){this.userProfile={…res};Object.keys(this.userProfile).forEach((item)=>this.formModel[item]=this.userProfile[item])
。在此之后,将标志设为true。这样,您就有了响应的默认副本以及分配给formModel的新副本。非常乐意提供帮助:)