0

I have an object that I would like to use in a view component, PersistedWaitlist:

export class PersistedWaitlist extends Waitlist implements Identifiable     {

  private items: PersistedWaitlistItem[];

  constructor(public readonly id: number, 
    createdAt: Date,
    name: string) {
    super(createdAt, name);
    this.items = new Array();
  }

  addItem(waitlistItem: PersistedWaitlistItem) {
    this.items.push(waitlistItem);
  }

  getItems(): Array<PersistedWaitlistItem> {
    return this.items;
  }
}

The view component is injected with an Observable persisted waitlist, and I would like to display each of its items. To do so, I have the following component:

@Component({
  selector: 'app-waitlist',
  templateUrl: './waitlist.component.html',
  styleUrls: ['./waitlist.component.css']
})
export class WaitlistComponent implements OnInit {

  @Input()
  waitlist: Observable<PersistedWaitlist>

  constructor() {
  }

  ngOnInit() {}

}

And here is the template:

<div id = "waitlist-root">
  <div id="waitlist-container">
    <app-waitlist-item *ngFor="let item of (waitlist | async).getItems()" [item]="item"></app-waitlist-item>
  </div>
</div>

Note the ngFor loop here: I am trying to access getItems() method of the waitlist object, but I am getting the following error:

WaitlistComponent.html:3 ERROR TypeError: Cannot read property 'getItems' of undefined

Does anyone know of the best way of reading the property of an Observable in a template? One approach I have considered is extracting the items array in the view component's constructor and making a separate Observable out of it, but I am not sure how to do that either.

scottysseus
  • 1,922
  • 3
  • 25
  • 50

1 Answers1

2

Try adding a safe navigation operator ? since getItems could be null when you try to access it as you are making a call asynchronously.

 <app-waitlist-item *ngFor="let item of (waitlist | async)?.getItems()"
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396