"this" 在 ngOnInit 中变为未定义

"this" becomes undefined in ngOnInit

"this" 在 ngOnInit

中变为未定义

我正在尝试将回调返回的对象推送到全局定义的数组中。

但它给出了

的错误

"cannot read property of undefined"

export class ItemsComponent implements OnInit {
items: Item[];
devices: any[];
constructor(private itemService: ItemService) {
    this.devices = new Array();
}
ngOnInit(): void {
    bluetooth.isBluetoothEnabled().then(
        enabled => console.log("Enabled ? " + enabled)
    );
    bluetooth.startScanning({
        serviceUUIDs: [],
        seconds: 4,
        onDiscovered: function(peripheral) {
            this.devices.push(peripheral);
        }
    }).then(function() {
        console.log("scanning complete");
    }, function(err) {
        console.log("error while scanning: " + err);
    });
    this.items = this.itemService.getItems();
}}

我在

收到这个错误
this.devices.push(peripheral);

您应该使用 Arrow Function 来掌握正确的 this 内部函数。

onDiscovered: function(peripheral)

应该是

onDiscovered:(peripheral) => {

}