You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ionic 6框架中导入Cordova BLE插件报错的技术求助

Ionic 6 中 cordova-plugin-ble-central 导入错误解决方法

你的导入方式不正确,报错原因是该插件的类型定义文件并非标准ES模块,无法通过import {BLE} from 'cordova-plugin-ble-central';的方式导入。以下是适配Ionic 6的正确处理步骤:

1. 移除错误的导入与注册

打开app.module.ts,删除以下内容:

  • import { BLE } from 'cordova-plugin-ble-central';
  • providers数组中的BLE项

修改后的app.module.ts示例:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }],
  bootstrap: [AppComponent],
})
export class AppModule {}

2. 添加类型声明

在项目的src目录下创建typings文件夹,新建cordova-ble.d.ts文件,添加以下类型声明(可根据需要补充API方法):

declare module 'cordova-plugin-ble-central' {
  export interface BLEDevice {
    id: string;
    name: string;
    rssi: number;
    advertising?: any;
  }

  export interface BLE {
    scan(services: string[], seconds: number, success: (device: BLEDevice) => void, error: (err: any) => void): void;
    connect(deviceId: string, connectSuccess: () => void, disconnectError: (err: any) => void): void;
    disconnect(deviceId: string, success?: () => void, error?: (err: any) => void): void;
    // 其他需要用到的API方法
  }
}

declare var ble: cordova-plugin-ble-central.BLE;

3. 在组件/服务中使用插件

在需要使用BLE功能的组件或服务顶部,通过declare var ble: cordova-plugin-ble-central.BLE;声明变量,之后即可调用插件API:

import { Component } from '@angular/core';
declare var ble: cordova-plugin-ble-central.BLE;

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  scanDevices() {
    // 扫描周围BLE设备,扫描时长5秒
    ble.scan([], 5, 
      (device) => {
        console.log('发现设备:', device);
      },
      (error) => {
        console.error('扫描失败:', error);
      }
    );
  }
}

注意事项

  • Cordova插件仅能在真机或模拟器环境运行,ionic serve的浏览器环境下无法加载插件,开发时可添加判断:
if (typeof ble !== 'undefined') {
  this.scanDevices();
} else {
  console.log('BLE插件仅支持真机环境,请在真机或模拟器中运行');
}

内容的提问来源于stack exchange,提问作者kaydrae

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 13:25:50