我有一个类,其中包含一个称为LearningElementDTO的对象的数组,该对象正在ngOnInit()方法上与observable异步初始化。 我的问题是当我尝试在加载组件时引用此数组时,出现错误: 无法读取未定义的属性“ 0”
这里的问题是,在初始化之前,我引用的对象是LearningElementDTO [0]。
private learningElements: LearningElementDTO[];
constructor(private service: LearningService) { }
ngOnInit() {
this.loadData();
// here is where the undefined problem happens
console.log(this.learningElements[0].name);
}
private loadData(): void {
this.service.getLearningElements().subscribe(
(reponse: any) => {
this.learningElements = reponse;
}
);
}
}
有什么解决方法可以避免引用以相同方式初始化的对象?
答案 0 :(得分:1)
您可以使用pipe
:
private learningElements: LearningElementDTO[];
constructor(private service: LearningService) { }
ngOnInit() {
this.loadData().subscribe(reponse => {
console.log(this.learningElements[0].name);
});
}
private loadData(): Observable<LearningElementDTO[]>{
return this.service.getLearningElements().pipe(
map((reponse: any) => {
this.learningElements = reponse;
return response;
})
);
}
}
答案 1 :(得分:1)
执行您的console.log
时,响应尚未返回。在将服务器响应分配给本地变量subscribe
this.learningElements
函数中
this.service
.getLearningElements()
.subscribe(response => {
this.learningElements = response;
console.log(this.learningElements[0].name);
});