Javascript &引用;推送();到Typescript中的数组

Javascript &引用;推送();到Typescript中的数组,javascript,typescript,Javascript,Typescript,我有以下代码,用于扫描蓝牙设备,对于找到的每个设备,我都希望将该设备添加到阵列中 devices: Observable<Array<string>>; bluetoothAdd() { this.isScanning = true; var plusIcon = this.page.getViewById("add"); plusIcon.style.opacity = 0; var self = this; bluetoo

我有以下代码,用于扫描蓝牙设备,对于找到的每个设备,我都希望将该设备添加到阵列中

devices: Observable<Array<string>>;

bluetoothAdd() {
    this.isScanning = true;
    var plusIcon = this.page.getViewById("add");
    plusIcon.style.opacity = 0;

    var self = this; 
    bluetooth.hasCoarseLocationPermission().then(
        function (granted) {
            if (!granted) {
                bluetooth.requestCoarseLocationPermission();
            } else {
                bluetooth.startScanning({
                    serviceUUIDs: ["133d"],
                    seconds: 4,
                    onDiscovered: function (peripheral) {
                        console.log("Periperhal found with UUID: " + peripheral.UUID);
                        this.devices.push(peripheral); // <- Problem Line
                    }
                }).then(function () {
                    console.log("scanning complete");
                    self.isScanning = false;
                    plusIcon.style.opacity = 1;
                }, function (err) {
                    console.log("error while scanning: " + err);
                });
                this.isScanning = false;
            }
        });
}
装置:可观察;
bluetoothAdd(){
this.isScanning=true;
var plusIcon=this.page.getViewById(“添加”);
plusIcon.style.opacity=0;
var self=这个;
bluetooth.hasRoughLocationPermission()。然后(
功能(已授予){
如果(!授予){
bluetooth.requestRouseLocationPermission();
}否则{
bluetooth.startScanning({
serviceUUIDs:[“133d”],
秒:4,
发现:功能(外围设备){
log(“发现UUID为+peripal.UUID的外围设备”);

this.devices.push(peripheral);//您已将设备定义为数组的可观察
设备:可观察
,而不是可以调用push()函数的数组
设备:数组

它与TypeScript无关,这只是的正常Javascript规则

问题指向所发现的函数,而不是类

您可以通过使用已定义的self变量或重写代码以使用箭头函数来修复它,如下所示:

装置:可观察;
bluetoothAdd(){
this.isScanning=true;
var plusIcon=this.page.getViewById(“添加”);
plusIcon.style.opacity=0;
bluetooth.hasRoughLocationPermission()。然后(
(准予)=>{
如果(!授予){
bluetooth.requestRouseLocationPermission();
}否则{
bluetooth.startScanning({
serviceUUIDs:[“133d”],
秒:4,
onDiscovered:(外围设备)=>{
log(“发现UUID为+peripal.UUID的外围设备”);
此.devices.push(外围设备);//{
控制台日志(“扫描完成”);
this.isScanning=false;
plusIcon.style.opacity=1;
},(错误)=>{
log(“扫描时出错:+err”);
});
this.isScanning=false;
}
});
}
此外,正如Bhabishya指出的那样,设备的类型是可观察的。该类型没有定义推送方法。相反,它将能够发射设备阵列

如果您只需要一个数组,那么还应该将设备更改为一个字符串数组,而不是一个可观察的字符串数组

devices: Array<string>;
设备:阵列;
您还必须对其进行初始化

devices: Array<string> = [];
devices:Array=[];

这与TypeScript无关。
不是你所期望的。请看。你可以使用
self
though你确定
这个问题吗?在他的onDiscovered函数中,
This
应该指类,因为他使用arows,与函数不同,箭头共享相同的词法
This
作为它们的周围代码。没有新的上下文。@PaulBoutes在原始文章中没有箭头函数。添加它们是修复方法。我的错,我没有看到!正如您所注意到的,该代码产生错误“属性‘push’在可观察的对象上不存在…”,那么我如何实现我想要的结果呢?即,将找到的每个新设备添加到阵列中?只需按照另一个answe中的建议将其设置为一个简单的阵列。我将更新我的答案。