Home > Software engineering >  Object is possibly 'null'.ngtsc(2531)
Object is possibly 'null'.ngtsc(2531)

Time:09-27

Here am trying to loop through an observable using the async pipe and its showing that the object is null.

 <ul  *ngFor="let i of (ingredients | async).ingredient;let val=index">
    <a  style="cursor:pointer;" (click)="editIngredients(val)">{{i.name}} {{i.number}}</a>
    <br>
</ul>

export class ShoppingListComponent implements OnInit {
  ingredients:Observable<{ingredient:ingredients[]}>
  constructor(private scr:ShoppingService,private testingService:TestingServices,
    private store:Store<{ModuleActivateReducer:{ingredient:ingredients[]}}>) { }
  ngOnInit() {
    this.ingredients=this.store.select('ModuleActivateReducer')
    console.log(this.ingredients,"store data ing")
  }
  editIngredients(id:number){
    this.scr.ingdredientsById.next(id)
  }
}

CodePudding user response:

The expression ingredients | async will evaluate to null until the observable emits a value. So attempting to access a property like (ingredients | async).ingredient will initially give you an error.

You can avoid this by using optional chaining (?):

If the object is undefined or null, it returns undefined instead of throwing an error

<ul *ngFor="let i of (ingredients | async)?.ingredient">
  ...
</ul>
  • Related