[英]“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錯誤TypeError:未定義不是對象(正在評估'this.devices.push')
我在Typescript中工作,但我知道push函數是JS東西。 不知道如何在Typescript中執行此操作-我做錯了什么?
它無關打字稿,它是這只是普通的JavaScript規則。
問題這點到你給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>>
而不是可在其上調用push()函數的陣列devices: Array<string>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.