I am very new to TypeScript and Angular (version is the latest) and I need help. I have declared 2 interfaces, one nested within the other and is an array of the nested interface.
export interface ModelOuter {
modelInners?: ModelInner[];
errorMessage : string;
}
export interface ModelInner {
prop1: string;
}
Now I am trying to call a service within my component, and this is my code,
export MyComponent implements OnInit {
modelOuter : ModelOuter | undefined; //I need help here
modelInner: ModelInner[] |undefined; //Do I really need this? If yes,how do I initialize it?
//other ngOnInit code block goes here and within ngOnInit I am calling the below block
this.myService.getModels()
.subscribe((data: ModelOuter)=> {
this.modelOuter : data;
if (data.modelInner.length > 0) {
this.modelInner = data.modelInner;
modelOuter.modelInner = this.modelInner;
}
}
No matter how much I try, on my template HTML, I am getting modelInner is Undefined error. My question is, how do I initialize both my outer interface and the nested interface in one line within my component and how do I assign both these objects within my service.subscribe block, so that I don’t get the undefined error on my template HTML?
Thanks!
2
Answers
I was able to get the initialization right finally.
should be replaced by:
and then in my subscribe block, I just need
Checking the presence of
modelInner
in the if condition should help