财产在承诺中未定义,但在承诺之外工作

时间:2018-02-28 14:41:36

标签: angular typescript

我需要根据另一个不同对象的数组过滤数组,但是使用相同的关键字段。这是我到目前为止所得到的,但我不确定为什么我会收到错误。

@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

所以this.accessoriesToAdd在我的控制台窗口中显示一个值,但是当我尝试在我的forEach中执行相同的操作时,它会出错。

1 个答案:

答案 0 :(得分:2)

而不是:

function(aa) { }

使用:

(aa) => { }

然后,在调用this时,您将可以访问EquipmentComponent。 如下例所示:

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