Javascript “推()”到打字稿中的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36667055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:22:47  来源:igfitidea点击:

"push()" to an array in Typescript

javascripttypescript

提问by George Edwards

I have the following code, to scan for a Bluetooth device, which for every device found, I want to add the device to an array.

我有以下代码,用于扫描蓝牙设备,对于找到的每个设备,我想将该设备添加到数组中。

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;
            }
        });
}

However, this code throws the following error:

但是,此代码会引发以下错误:

JavaScript error: file:///app/Pages/Home/home.component.js:99:37: JS ERROR TypeError: undefined is not an object (evaluating 'this.devices.push')

JavaScript 错误:file:///app/Pages/Home/home.component.js:99:37: JS ERROR TypeError: undefined is not an object (evaluating 'this.devices.push')

I am working in Typescript, but I know the push function is a JS thing. Not sure how I would do this in Typescript - what have I done wrong?

我在打字稿工作,但我知道推送功能是一个 JS 的东西。不知道我会如何在 Typescript 中做到这一点 - 我做错了什么?

回答by toskv

It has nothing to do with TypeScript, it's just normal Javascript rules for this.

它与 TypeScript 无关,它只是针对this 的普通 Javascript 规则。

The problem thispoints to the function you give to onDiscoveredinstead of the class.

指向您提供给onDiscovered而不是类的函数的问题。

You can fix it by using the selfvariable you have defined or by rewriting the code to use arrow functions instead, like this:

您可以通过使用您定义的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;
            }
        });
}

Also, as Bhabishya pointed out the type of devices is Observable. That type has no push method defined on it. Instead it will be able to emitan array of Devices.

此外,正如 Bhabishya 指出的,设备类型是可观察的。该类型没有定义 push 方法。相反,它将能够发出一组设备。

If all you need is an array you should also change the devicesto be an array of string, instead of an Observable of array of string.

如果您只需要一个数组,您还应该将设备更改为字符串数组,而不是字符串数组的 Observable。

devices: Array<string>;

You will also have to initialize it.

您还必须对其进行初始化。

devices: Array<string> = [];

回答by Bhabishya Kumar

You have defined devices as Observable of array devices: Observable<Array<string>>and not an array devices: Array<string>on which you can call the push() function.

您已将设备定义为数组的 Observable,devices: Observable<Array<string>>而不是devices: Array<string>您可以调用 push() 函数的数组。