2017-06-21 26 views
1
变得不确定

“这个”成为ngOnInit“本”在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); 

回答

2

得到这个错误,你应该使用Arrow Function得到坚持正确this内部功能。

onDiscovered: function(peripheral) 

应该是

onDiscovered:(peripheral) => { 

} 
+0

这似乎是正确的,但如果我使用 this.devices.forEach(元素=> { 的console.log(element.UUID); }); 在“那么”,它给出了相同的错误 –

+0

进一步,我期待this.devices可用于UI,以便我可以将它绑定到某个元素。 –

+2

@RaasMasood然后在你希望得到词汇这个箭头的地方制作每一个函数。这是箭头的用途。 – estus