Property bluetooth does not exist on type ‘Navigator'
Asked Answered
R

3

6

I integrated sample code into my Angular 6 project. But there some compile errors. One of these errors is: Property 'bluetooth' does not exist on type 'Navigator'.

Why this error happens and how can I solve it?

Rettarettig answered 12/7, 2018 at 6:11 Comment(2)
Gonna need some code..Mellins
this means that navigator object doesn't have any property named 'bluetooth', if you have navigator as an interface or class in typescript , just add that property to solve itBuckskins
S
9

Use this below module to install types of web-bluetooth api. Which you can use to define types of navigator blutooth api objects.

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

Now if you need not specify the exact type of navigator object (& its properties) then you can do following:

let mobileNavigatorObject: any = window.navigator;
if(mobileNavigatorObject && mobileNavigatorObject.bluetooth) {
  // Here write your logic of mobileNavigatorObject.bluetooth.requestDevice();
}
Sokul answered 12/7, 2018 at 6:28 Comment(0)
G
11

I'm not sure why this error happens but you can fix it by installing the types,npm install --save-dev @types/web-bluetooth, and using a triple-slash directive, /// <reference types="web-bluetooth" />, like so:

/// <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);
    }
  }
}
Gynoecium answered 23/7, 2020 at 16:20 Comment(0)
S
9

Use this below module to install types of web-bluetooth api. Which you can use to define types of navigator blutooth api objects.

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

Now if you need not specify the exact type of navigator object (& its properties) then you can do following:

let mobileNavigatorObject: any = window.navigator;
if(mobileNavigatorObject && mobileNavigatorObject.bluetooth) {
  // Here write your logic of mobileNavigatorObject.bluetooth.requestDevice();
}
Sokul answered 12/7, 2018 at 6:28 Comment(0)
S
2

Try to install the following npm module:

npm install --save @types/web-bluetooth

and insert this row in the top of your code:

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

Plus if you receive the following error:

Failed to execute 'requestDevice' on 'Bluetooth': Must be handling a user gesture to show a permission request.

You have too call the bluetooth function from a user call, ex. call the function from a button.

Sarson answered 23/4, 2021 at 14:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.