【问题标题】:navigator.bluetooth not working in typescriptnavigator.bluetooth 在打字稿中不起作用
【发布时间】:2018-12-25 18:59:12
【问题描述】:

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

控制台出错(如果在 Ts 中运行代码):

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

// 打字稿/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

操作系统:linux x64

角度:6.0.9

【问题讨论】:

    标签: angular typescript google-chrome-devtools web-bluetooth


    【解决方案1】:

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

    【讨论】:

    • 是的,当我在一个角度生命周期中进行测试调用之前,我通过单击一个按钮调用该函数时能够解决该问题,因此它无法正常工作。头疼了好久终于解决了,谢谢!
    猜你喜欢
    • 2016-06-16
    • 1970-01-01
    • 2018-11-23
    • 2023-04-07
    • 2020-03-18
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 2017-11-28
    相关资源
    最近更新 更多