Cooper
Cooper

Reputation: 197

Property is undefined in promise but works outside of the promise

I need to filter an array based on another array of different object but with the same key field. This is what I have so far but I'm not sure why I'm getting the error.

@Component({
  selector: 'equipment',
  templateUrl: './equipment.component.html',
  styleUrls: ['./equipment.component.css']
})
export class EquipmentComponent implements OnInit {
  @Input() equip: OrderMachine
  @Input() price: ProductPricing
  inEdit = false

  pricing: ProductPricing[]
  accessories: ProductMachineAccessories[]
  accessoriesToAdd: ProductMachineAccessories[]
  constructor(private orderService: OrderService) { }

  ngOnInit() {
    this.pricing = this.orderService.getPricing()

    this.orderService.getAccessories(this.equip.machineId).then((accessories) => {
      this.accessories = accessories
      this.accessoriesToAdd = accessories
      console.log(this.accessoriesToAdd.length)  // No error -- displays a number in the console
       
       this.equip.accessories.forEach(function(aa) {
         console.log(this.accessoriesToAdd.length) //error at the bottom
      //    this.accessoriesToAdd = this.accessoriesToAdd.filter(a => a.accessoryId !== aa.accessoryId)
          
        })
    })


    }
}


//core.es5.js:1020 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'accessoriesToAdd' of undefined
//TypeError: Cannot read property 'accessoriesToAdd' of undefined
//    at equipment.component.ts:39

So this.accessoriesToAdd displays a value in my console window but then when I try and do the same thing in my forEach it errors out.

Upvotes: 0

Views: 98

Answers (1)

James Woodruff
James Woodruff

Reputation: 973

Instead of:

function(aa) { }

Use:

(aa) => { }

Then you'll have access to the EquipmentComponent when calling this. Like the below example:

...
this.equip.accessories.forEach( (aa) => {
     console.log(this.accessoriesToAdd.length); // No errors    
})
...

Upvotes: 2

Related Questions