"push()"到Typescript中的数组
"push()" to an array in Typescript
我有以下代码,用于扫描蓝牙设备,对于找到的每一个设备,我都想将该设备添加到阵列中。
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;
}
});
}
但是,此代码会引发以下错误:
JavaScript错误:file:///app/Pages/Home/home.component.js:99:37:JS ERROR TypeError:undefined不是对象(正在评估"this.devices.push")
我在Typescript中工作,但我知道push函数是JS的东西。不知道我会如何在打字中做到这一点——我做错了什么?
它与TypeScript无关,它只是this的普通Javascript规则。
问题this指向您赋予onDiscovered的函数,而不是类。
您可以使用您定义的self变量来修复它,或者重写代码以使用箭头函数,如下所示:
devices: Observable<Array<string>>;
bluetoothAdd() {
this.isScanning = true;
var plusIcon = this.page.getViewById("add");
plusIcon.style.opacity = 0;
bluetooth.hasCoarseLocationPermission().then(
(granted) => {
if (!granted) {
bluetooth.requestCoarseLocationPermission();
} else {
bluetooth.startScanning({
serviceUUIDs: ["133d"],
seconds: 4,
onDiscovered: (peripheral) => {
console.log("Periperhal found with UUID: " + peripheral.UUID);
this.devices.push(peripheral); // <- Problem Line
}
}).then(() => {
console.log("scanning complete");
this.isScanning = false;
plusIcon.style.opacity = 1;
}, (err) => {
console.log("error while scanning: " + err);
});
this.isScanning = false;
}
});
}
此外,正如Bhabishya所指出的,这种类型的设备是可观测的。该类型上没有定义push方法。相反,它将能够发射一个设备数组。
如果您只需要一个数组,那么还应该将设备更改为字符串数组,而不是字符串数组的Observable。
devices: Array<string>;
你还必须初始化它。
devices: Array<string> = [];
您已经将设备定义为数组devices: Observable<Array<string>>
的Observable,而不是可以在其上调用push()函数的数组devices: Array<string>
。
相关文章:
- 如何在映射数组中添加换行符
- javascript结合了数组和字典
- "push()"到Typescript中的数组
- 如何获得"材料”;数组
- 添加前缀“#"到数组中的某些字符串值
- "无法读取属性'id'未定义的“;解析工厂中声明的数组时
- 如何替换“"带有'"'在JavaScript的数组中
- "indexOf“;作为“”中数组的键;对于在“;cicle在IE8中
- 在JSON中POST一个js::数组,得到"undefined:undefined”;
- jQuery:"类“;使用对象数组
- JQuery:获取"数据值=n〃;在shuffle数组中可见的li
- 获取对象"值“;在数组中
- "甚至最后一个“;数组javascript练习
- 用javascript a la"来强调多维数组中的所有子元素;数学”;
- 基于"字符串"的任意数组元素;种子
- 数组方法"some"的使用:收到意外的结果
- 为什么它不适用于阶级".1〃;在数组中,并且可以很好地用于其他类
- jQuery:生成"name”;动态属性数组
- 我如何从由“”创建的数组中调用元素;document.getElementBytag()"
- 如何删除逗号和""来自JavaScript数组