我有一个表单,想在显示后向表单字段添加默认值,所以基本上我有 2 个函数 #1 用于从后端检索数据 #2 显示表单:
person$: any;
ngOnInit() {
this.getPersonData(123)
this.buildPersonForm()
}
getPersonData(id: number) {
this.personService.getDetails(id)
.subscribe((data) => {
this.person$ = data
}
}
buildPersonForm() {
// Here I want to access this.person$.firstname
console.log(this.person$.firstname) // undefined
this.PersonForm = this.fb.group({
firstname: [null, Validators.required],
})
}
在 html 模板中,如果我按如下方式使用它,它会起作用:
<input matInput placeholder="Firstname" formControlName="firstname" value="{{person$?.firstname}}">
但我想知道如何在组件内部而不是在 html 模板中访问它。
Angular CLI: 7.0.2
Node: 10.12.0
OS: darwin x64
Angular:
...
Package Version
------------------------------------------------------
@angular-devkit/architect 0.10.2
@angular-devkit/core 7.0.2
@angular-devkit/schematics 7.0.2
@schematics/angular 7.0.2
@schematics/update 0.10.2
rxjs 6.3.3
typescript 3.1.3
最佳答案
只需在 getPersonData 可观察完成时调用 buildPersonForm
ngOnInit() {
this.getPersonData(123);
}
getPersonData(id: number) {
this.personService.getDetails(id)
.subscribe((data) => {
this.person$ = data
},
null,
() => this.buildPersonForm()
}
另一种方式只是 buildPersonForm
在 subscribe 的 next 方法体中
ngOnInit() {
this.getPersonData(123);
}
getPersonData(id: number) {
this.personService.getDetails(id)
.subscribe((data) => {
this.person$ = data;
this.buildPersonForm();
}
}
您可以使用async/await的最后一种方式
async ngOnInit() {
this.person$ = await this.getPersonData(123).toPromise();
this.buildPersonForm();
}
关于 Angular ,在获得 promise 值后无法访问另一个函数中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53665070/