在ngOnInit中,“this”变为未定义

时间:2017-06-21 20:11:48

标签: javascript angularjs variables angular-promise

“此”在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);

1 个答案:

答案 0 :(得分:3)

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

onDiscovered: function(peripheral)

应该是

onDiscovered:(peripheral) => {

}