0

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.

Cooper
  • 167
  • 1
  • 12
  • 2
    `this` is not what you think it is. Use an arrow function. – SLaks Feb 28 '18 at 14:42
  • 1
    Possible duplicate of [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Joe Clay Feb 28 '18 at 14:45

1 Answers1

2

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    
})
...
James Woodruff
  • 935
  • 6
  • 10