我在ngOnInit()函数中为我的变量设置值时遇到了一些麻烦。我试图在设置后在控制台中看到变量,但我只收到" undefined"。如何使它工作?
export class GalleryComponent implements OnInit {
actualModelType: modelInterface[];
femaleModels: modelInterface[];
constructor(private _femaleModelsService: FemaleModelsService) {
this.actualModel = null;
this.clicked = false;
}
ngOnInit() {
this._femaleModelsService.getFemaleModels()
.subscribe( responseFemaleModelsData => this.femaleModels = responseFemaleModelsData );
this.actualModelType = this.femaleModels;
console.log( this.actualModelType, this.femaleModels );
}
}
答案 0 :(得分:2)
您在这里遇到的问题是,您正在调用来自FemaleModelsService的数据,但您还要分配您尚未拥有的值。
Observable和promises是异步的,所以你必须等待他们的响应才能操纵他们返回给你的东西。正如jonrsharpe所解释的那样,你必须在回调中获取数据才能完成你想要的工作。
试试这个:
ngOnInit() {
this._femaleModelsService.getFemaleModels().subscribe(
responseFemaleModelsData => {
this.femaleModels = responseFemaleModelsData;
this.actualModelType = this.femaleModels;
console.log(this.actualModelType, this.femaleModels);
}
);
}