【发布时间】:2018-05-01 02:54:22
【问题描述】:
我有一个问题,也许我不明白该怎么做,但是当我尝试在角度 ngOnInit 期间从 HttpRequest 捕获数据时,我的 console.log 会返回一个“未定义”值。 问题是,当我在模板视图中使用此值时,它会起作用!
这是我的组件
export class ReferentielFormComponent implements OnInit {
id: number;
currentUser;
referentiel;
progressValue: number;
formGroup: FormGroup;
isNew: boolean;
constructor(private service: AppService,
private referentiels: ReferentielService,
private router: ActivatedRoute,
private config: NgbTabsetConfig) {
}
ngOnInit() {
this.router.params.subscribe((params: Params) => this.id = params['id']);
if (this.id) {
this.referentiels.getReferentiel(this.id).subscribe(data => this.referentiel = data);
} else {
this.referentiel = {};
}
this.isNew = !this.referentiel;
console.log(this.referentiel);
console.log(this.isNew);
this.progressValue = 20;
this.formGroup = new FormGroup({
titre: new FormControl(!this.isNew ? this.referentiel.titre : '', [
Validators.required,
]),
description: new FormControl(!this.isNew ? this.referentiel.description : '', [
Validators.required,
])
});
}
}
变量 this.referentiel 返回一个未定义的值,因此我无法将我的表单绑定到现有值...
有什么建议吗?
【问题讨论】:
-
this.id可以为空吗? -
这个id不为空!问题是 this.referentiel 在 ngOnInit 第一次传入该函数时为空。我不知道为什么!
-
默认变量是未定义的,因此引用是未定义的。当一个值被分配给它时,它就被定义了。如果 id 存在,它只发生在 subscribe 函数中。到订阅完成时,console.log 和 formgroup 已经被执行了
-
@KrishnanunniJeevan 是的,我明白了!这正是我的问题:/我现在应该怎么做?
-
@ValentinFerey,正如我已经回答的那样,将使用引用变量的逻辑移动到一个公共函数中。从 else 条件和订阅函数内部调用它
标签: angular http typescript subscribe ngoninit