Angular 为什么onCompleted for Observable没有形式值?
目标:我想获得角度反应形式上输入的值。 我看到它是空的,除非我超时,所以我尝试使用observable的onCompleted() 根据和 我想我需要使用addControl方法。但是,我无法获取该值(它以null形式打印到控制台)Angular 为什么onCompleted for Observable没有形式值?,angular,typescript,rxjs,observable,angular-reactive-forms,Angular,Typescript,Rxjs,Observable,Angular Reactive Forms,目标:我想获得角度反应形式上输入的值。 我看到它是空的,除非我超时,所以我尝试使用observable的onCompleted() 根据和 我想我需要使用addControl方法。但是,我无法获取该值(它以null形式打印到控制台) ngOnInit(){ GetUserProfile(); } 公共GetUserProfile() { this.aa.GetProfile(id).subscribe(resp=>{ this.user=resp; this.aa.GetPref(id).sub
ngOnInit(){
GetUserProfile();
}
公共GetUserProfile()
{
this.aa.GetProfile(id).subscribe(resp=>{
this.user=resp;
this.aa.GetPref(id).subscribe(resp=>{
this.email=resp.email;
//表单配置
这个.createForm();
this.isLoaded=true;
})
},
错误=>{
控制台日志(err);
},
() => {
console.log(“登录已完成?”);
this.spanish=(document.getElementById(“spanish2”)).value
console.log(this.西班牙语);
this._profileForm.addControl('spanish3',newformcontrol(this.西班牙语));
}
);
}
createForm(){
this.\u pForm=this.fb.group({
“spanish2”:新的FormControl()
});
}
实际结果:它打印出“完成时?”,但也表示“无法读取null的属性‘值’”,参考:
this.spanish = (<HTMLInputElement>document.getElementById("spanish2")).value
this.spanish=(document.getElementById(“spanish2”)).value
我期望它在此时具有该值。它只有在使用setTimeout时才有效
HTML:
我的个人资料
该块由依赖于异步设置的类属性isLoaded的*ngIf
包围。在执行document.getElementById('spanish2')
时,该输入可能根本不存在。您也不应该指望setTimeout()
,因为根据异步调用解析所需的时间,时间可能会有所不同。@AlexanderStaroselsky如果我抓取元素并尝试打印到控制台,在if(this.isLoaded)内。。什么也没发生。我错过了什么?我应该只创建一个单独的隐藏表单,而不这样做来获取其中的值吗?是的,即使在isLoaded
设置为渲染不是即时的之后将其放置正确,这仍然是一个问题。您应该避免完全使用document.getElementById()
。请尝试使用被动表单提供的API来获取/设置值。@AlexanderStaroselsky,我使用getElementById的唯一原因是我正在使用i18n将英语翻译成西班牙语,因此在typescript中不知道插值。我正在创建隐藏输入并获取其i18n翻译值,然后在typescript中使用该动态翻译值将其转换为真实形式。该块由一个*ngIf
包围,该块依赖于异步设置的类属性isLoaded
。在执行document.getElementById('spanish2')
时,该输入可能根本不存在。您也不应该指望setTimeout()
,因为根据异步调用解析所需的时间,时间可能会有所不同。@AlexanderStaroselsky如果我抓取元素并尝试打印到控制台,在if(this.isLoaded)内。。什么也没发生。我错过了什么?我应该只创建一个单独的隐藏表单,而不这样做来获取其中的值吗?是的,即使在isLoaded
设置为渲染不是即时的之后将其放置正确,这仍然是一个问题。您应该避免完全使用document.getElementById()
。请尝试使用被动表单提供的API来获取/设置值。@AlexanderStaroselsky,我使用getElementById的唯一原因是我正在使用i18n将英语翻译成西班牙语,因此在typescript中不知道插值。我创建隐藏的输入并获取它们的i18n翻译值,然后在typescript中使用该动态翻译值将其放入真实的表单中。
this.spanish = (<HTMLInputElement>document.getElementById("spanish2")).value
<mat-card class="patient-card">
<mat-card-title class="text-center">
My Profile
</mat-card-title>
<mat-card-content>
<div fxLayoutAlign="center center" *ngIf="!isLoaded">
<mat-spinner></mat-spinner>
</div>
<div *ngIf="isLoaded">
<form [formGroup]="_pForm" novalidate>
<mat-form-field class="input-width" [class.hide-element]="true">
<input matInput placeholder="Spanish" id="spanish2" formControlName="spanish2" i18n-value="@@AiBrErQv_G2_91" value="Spanish">
</mat-form-field>
</form>
</div>
</mat-card-content>
</mat-card>