Home > Net >  Angular: ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading
Angular: ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading

Time:02-12

I try execute on my cards.component.ts

    notices: notice[];

    ngOnInit() {
      this.dataService.getCards().subscribe( data => { this.notices = data });
      this.notices.forEach(n => {
        console.log('test')
      });
    }

I only want show something in console for every item is on "notices" but show me this error

ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'forEach')

CodePudding user response:

Array notices should be initialized in field declaration or in constructor of component

notices: notice[] = [];

or

constructor() { this.notices = [] }

CodePudding user response:

Most likely your subscribe is getting called after your call to forEach The best fix would be to initialize your notices to an empty array and then loop through this.notices inside the subscribe call:

notices: notice[] = [];

ngOnInit() {
  this.dataService.getCards().subscribe( data => { 
  this.notices = data 
  this.notices.forEach(n => {
     console.log('test')
  });
 });     
}
  • Related