navigator.bluetooth 无法使用打字稿

navigator.bluetooth not working in typescript

我正在尝试进行 chrome 蓝牙 API 调用,但我无法通过打字稿获得成功。我已经尝试在 html () 中应用文件,但也无济于事。 但是如果你复制代码并将其粘贴到浏览器控制台,代码 运行s 完美:(

控制台错误(如果 运行 Ts 中的代码):

DOMException: Must be handling a user gesture to show a permission request.

// Typescript/TS:

requestBluetooth() {
    (window.navigator as any).bluetooth.requestDevice({ filters: [{ services: [this.PRINT_SERVICE_CODE] }] })
      .then(device => {
        return device.gatt.connect();
      })
      .then(server => {
        return server.getPrimaryService(this.PRINT_SERVICE_CODE);
      })
      .then(service => {
        return service.getCharacteristic('00002af1-0000-1000-8000-00805f9b34fb');
      })
      .then((characteristic) => {
        this.sendTextData(characteristic);
      })
      .catch(error => console.log(error));
  }

sendTextData(characteristic) {
    // Get the bytes for the text
    const encoder = new TextEncoder('UTF-8');
    const text = encoder.encode('TESTETSETS' + '\u000A\u000D');
    return characteristic.writeValue(text)
      .then(() => console.log('Write done.'));
  }

// 在控制台浏览器中工作:

const PRINT_SERVICE_CODE = '000018f0-0000-1000-8000-00805f9b34fb';

const sendTextData = (function (characteristic) {
  const encoder = new TextEncoder('UTF-8');
  const text = encoder.encode('TESTETSETS' + '\u000A\u000D');
  return characteristic.writeValue(text)
    .then(() => console.log('Write done.'));
})

const request = (function () {
  navigator.bluetooth.requestDevice({ filters: [{ services: [PRINT_SERVICE_CODE] }] })
  .then(device => {
    return device.gatt.connect();
  })
  .then(server => {
    return server.getPrimaryService(PRINT_SERVICE_CODE);
  })
  .then(service => {
    return service.getCharacteristic('00002af1-0000-1000-8000-00805f9b34fb');
  })
  .then((characteristic) => {
    this.sendTextData(characteristic);
  })
  .catch(error => console.log(error));
})

request();

//项目信息:

Angular CLI:6.0.8

节点:8.11.3

OS: linux x64

Angular: 6.0.9

requestBluetooth() 是否在用户手势(例如按钮单击)的事件处理程序中被调用?我现在找不到它,但我记得有一个与 Angular 相关的类似问题,其中某些类型的点击处理程序没有保留用户手势标记。