RRB
RRB

Reputation: 2116

Angular array: ERROR TypeError: Cannot read property of undefined

I am trying to display information from a web service but am getting the following error "ERROR TypeError: Cannot read property 'bu' of undefined". However the data that I wish to display is showing correctly. Here is a copy of the web service response and code.

{
    "bu": [
           {
            "id": 1,
            "bcluster": "R03 - Information Technology",
            "bsector": "P20 - CA SA",
            "bgroup": "319 - ITM as a Service (passthrough)",
            "bunit": "-"
           },
           {
            "id": 2,
            "bcluster": "R03 - Information Technology",
            "bsector": "Q04 - Information Management & Applications",
            "bgroup": "P36 - Softworks",
            "bunit": "001 - Softworks Licence & Maintenanc"
           }
         ]
}

HTML

  <ul class="list-group"  *ngFor="let item of vals.bu">
    <li class="list-group-item d-flex justify-content-between align-items-center">
      <button type="button" class="btn btn-info">{{item.id}}</button>
        <input type="text" class="input-group btn btn-light" [(ngModel)]="item.bunit">
      <button type="button" class="btn btn-primary">Update</button>
    </li>
  </ul>

TS

  ngOnInit(): void {
    this.http.get<DataResponse>(this.api.getBU()).subscribe(data => {
      this.vals = data;
    });
  }

Upvotes: 1

Views: 2104

Answers (2)

Sajeetharan
Sajeetharan

Reputation: 222582

You need to use safe navigation operator or *ngIf inorder to handle the delay of response from your asynchronous request,

 <button type="button" class="btn btn-info">{{item?.id}}</button>
        <input type="text" class="input-group btn btn-light" [(ngModel)]="item?.bunit">
      <button type="button" class="btn btn-primary">Update</button>
    </li>

EDIT

As mentioned in the comment, handle the null in your ngFor and remove it in the ngModel

<ul class="list-group"  *ngFor="let item of vals?.bu">
    <li class="list-group-item d-flex justify-content-between align-items-center">
      <button type="button" class="btn btn-info">{{item.id}}</button>
        <input type="text" class="input-group btn btn-light" [(ngModel)]="item.bunit">
      <button type="button" class="btn btn-primary">Update</button>
    </li>
</ul>

Upvotes: 4

Amit Chigadani
Amit Chigadani

Reputation: 29715

You should use safe navigation operator for vals?.bu. Because you are getting vals asynchronously.

<ul class="list-group"  *ngFor="let item of vals?.bu">
    <li class="list-group-item d-flex justify-content-between align-items-center">
      <button type="button" class="btn btn-info">{{item.id}}</button>
        <input type="text" class="input-group btn btn-light" [(ngModel)]="item.bunit">
      <button type="button" class="btn btn-primary">Update</button>
    </li>
  </ul>

Upvotes: 2

Related Questions