“此”在ngOnInit中未定义
我正在尝试将回调上返回的对象推送到全局定义的数组中。
但它给出了错误
“无法读取未定义的属性”
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);
答案 0 :(得分:3)
您应该使用Arrow Function
来掌握正确的this
内部功能。
onDiscovered: function(peripheral)
应该是
onDiscovered:(peripheral) => {
}