skip to Main Content

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


  1. Chosen as BEST ANSWER

    I was able to get the initialization right finally.

    modelOuter : ModelOuter | undefined; //I need help here
    modelInner: ModelInner[] |undefined; //Do I really need this? If yes,how do I initialize it?
    

    should be replaced by:

    modelOuter: ModelOuter  = {
    errorMessage: '',
    modelInners : []
    }
    

    and then in my subscribe block, I just need

    this.modelOuter = data;
    

  2. Checking the presence of modelInner in the if condition should help

    this.myService.getModels()
    .subscribe((data: ModelOuter)=> {
           this.modelOuter : data;
    
           if (data?.modelInner && data.modelInner.length > 0) {
             this.modelInner = data.modelInner;
             modelOuter.modelInner = this.modelInner;
           }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search