4

我将示例代码集成到我的 Angular 6 项目中。但是有一些编译错误。这些错误之一是:“导航器”类型上不存在属性“蓝牙”。

为什么会发生此错误,我该如何解决?

4

3 回答 3

8

使用下面的模块来安装 web-bluetooth api 的类型。您可以使用它来定义导航器蓝牙 api 对象的类型。

https://www.npmjs.com/package/@types/web-bluetooth

现在,如果您不需要指定导航器对象的确切类型(及其属性),那么您可以执行以下操作:

let mobileNavigatorObject: any = window.navigator;
if(mobileNavigatorObject && mobileNavigatorObject.bluetooth) {
  // Here write your logic of mobileNavigatorObject.bluetooth.requestDevice();
}
于 2018-07-12T06:28:47.607 回答
7

我不确定为什么会发生此错误,但您可以通过安装类型 ,npm install --save-dev @types/web-bluetooth并使用三斜杠指令来修复它/// <reference types="web-bluetooth" />,如下所示:

/// <reference types="web-bluetooth" />

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  title = 'myApp';

  async test() {
    try {
      const device = await navigator.bluetooth.requestDevice({
        filters: [
          {
            namePrefix: 'test',
          },
        ],
        optionalServices: ['test'],
      });
    } catch (error) {
      console.error(error);
    }
  }
}
于 2020-07-23T16:20:51.017 回答
0

尝试安装以下 npm 模块:

npm install --save @types/web-bluetooth

并在代码顶部插入这一行:

/// <reference types="web-bluetooth" />

另外,如果您收到以下错误:

无法在“蓝牙”上执行“requestDevice”:必须处理用户手势以显示权限请求。

您也可以从用户呼叫中调用蓝牙功能,例如。从按钮调用函数。

于 2021-04-23T14:59:10.130 回答