javascript - Ionic 2公共(public)变量和内部函数

标签 javascript function angular typescript ionic2

我在使用 Ionic 2 时遇到问题,尤其是 Angular 方面的问题。我的问题是我有一个名为“isConnected”的变量,当我想从函数的内部函数访问时,我不能。它说无法定义未定义的属性。如何从内部函数访问我的变量 isConnected?我尝试过这个:BleProvider.prototype.isConnected 但它不起作用。有人可以向我解释一下这是如何工作的吗?

export class BleProvider {

 public isConnected = false;
 public mDevice;

 constructor(public http: Http) {}

 connectToDevice(device){
  console.log('Connecting to device...');

  this.mDevice = device;
  setTimeout(
   ble.connectToDevice(
    device,
    onConnected,
    onDisconnected,
    onConnectError),
   500);

  function onConnected(device) {
    console.log("Connected to device: " + device.name);
    this.isConnected = true;
    console.log("isConnected variable status: " + this.isConnected);
  }
  function onDisconnected(device) {
    console.log('Disconnected from device: ' + device.name);
  }
  function onConnectError(error) {
    console.log('Connect error: ' + error);
  }
}

最佳答案

您应该使用arrow functions ,像这样:

export class BleProvider {

    public isConnected = false;
    public mDevice;

    constructor(public http: Http) { }

    connectToDevice(device) {
        console.log('Connecting to device...');

        this.mDevice = device;

        // Create the callbacks by using arrow functions () => {...}
        let onConnected = (device) => {
                console.log("Connected to device: " + device.name);
                this.isConnected = true;
                console.log("isConnected variable status: " + this.isConnected);
            },
            onDisconnected = (device) => {
                console.log('Disconnected from device: ' + device.name);
            },
            onConnectError = (error) => {
                console.log('Connect error: ' + error);
            }

        // You can also use an arrow function in the setTimeout! :)
        setTimeout(() => {
            ble.connectToDevice(device, onConnected, onDisconnected, onConnectError);
        }, 500);

    }
}

使用常规函数时,this 关键字引用函数本身,但使用箭头函数时,this 属性不会被覆盖并且仍然引用组件实例(您在其中定义了 isConnected 属性)。

关于javascript - Ionic 2公共(public)变量和内部函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44700689/

相关文章:

Javascript string.replace 正则表达式

c - 如何将字符串数组从函数传递给 main

Angular 6 在 "e2e/app"文件夹中生成服务

javascript - 模块 'FormBuilder' 导入了意外值 'AppModule'。请添加@NgModule 注解

javascript - 触发事件和调度事件有什么区别?

javascript - 如何修复: Dragged element not shown

arrays - 将数组和结构传递给 C 函数

javascript - 没有选择在 javascript 中复制变量,否则它不起作用

angular - 如何检测 ion-content 是否有滚动条?

javascript - polymer 铁-autogrow-textarea显示符号数