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

求问:在Ionic 3/Ionic 4应用中集成xdrip-js的完整流程经验

Hey there! I’ve walked through the full process of integrating xdrip-js into both Ionic 3 and Ionic 4 applications, so I can break down the key steps, configuration tweaks, and common pitfalls to help you get up and running smoothly.

1. Pre-Requisites

Before diving in, make sure you have:

  • A working Ionic 3 or 4 project (we’ll cover creating one if you don’t have it)
  • Node.js 12+ installed (LTS versions work best for compatibility)
  • Basic familiarity with Bluetooth Low Energy (BLE) concepts, since xdrip-js relies on BLE to connect to glucose monitors
  • The cordova-plugin-ble-central plugin (we’ll add this later, but it’s non-negotiable for BLE functionality)
2. Set Up Your Ionic Project

For Ionic 3:

Create a new project with the Ionic Angular template:

ionic start my-glucose-app blank --type=ionic-angular
cd my-glucose-app

For Ionic 4:

Use the Angular template (Ionic 4 shifted to Angular as the default framework):

ionic start my-glucose-app blank --type=angular
cd my-glucose-app
3. Install xdrip-js & Dependencies

First, install xdrip-js via npm:

npm install xdrip-js --save

Next, install the required BLE plugin for Cordova:

cordova plugin add cordova-plugin-ble-central

Note for Ionic 3 users: You may need to add polyfills for ES6+ features that xdrip-js uses. Open src/polyfills.ts and add these lines at the bottom:

import 'core-js/es7/array';
import 'core-js/es7/object';
4. Create a Reusable xdrip-js Service

To keep your code organized, wrap xdrip-js functionality in an Angular service. Generate a service with:

ionic generate service services/xdrip

Ionic 4 Service Code:

Replace the contents of src/services/xdrip.service.ts with this:

import { Injectable } from '@angular/core';
import * as xdrip from 'xdrip-js';

@Injectable({
  providedIn: 'root'
})
export class XdripService {
  private bluetoothManager: any;
  public glucoseUpdates: any[] = [];

  constructor() {
    this.initializeXdrip();
  }

  private initializeXdrip() {
    this.bluetoothManager = new xdrip.BluetoothManager();

    // Listen for device connection events
    this.bluetoothManager.on('deviceConnected', (device) => {
      console.log('Connected to:', device.name);
    });

    // Listen for new glucose readings
    this.bluetoothManager.on('glucoseData', (data) => {
      console.log('New glucose reading:', data);
      this.glucoseUpdates.push(data);
    });

    // Handle disconnections
    this.bluetoothManager.on('deviceDisconnected', () => {
      console.log('Device disconnected');
    });
  }

  // Scan for nearby BLE glucose monitors
  async scanForDevices(): Promise<any[]> {
    try {
      const devices = await this.bluetoothManager.scan();
      return devices.filter(device => device.name?.includes('Dexcom') || device.name?.includes('Medtronic')); // Filter common devices
    } catch (error) {
      console.error('Scan failed:', error);
      throw error;
    }
  }

  // Connect to a specific device by ID
  async connectToDevice(deviceId: string): Promise<void> {
    try {
      await this.bluetoothManager.connect(deviceId);
    } catch (error) {
      console.error('Connection failed:', error);
      throw error;
    }
  }

  // Disconnect from the current device
  disconnectDevice(): void {
    this.bluetoothManager.disconnect();
  }
}

Ionic 3 Adjustment:

Change the @Injectable() decorator to @Injectable() (no providedIn), then add the service to your app.module.ts providers array.

5. Configure App Permissions

BLE requires specific permissions on both Android and iOS. Update your config.xml (root project folder) with these entries:

<!-- Android Permissions -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- Required for scanning on Android 6+ -->

<!-- iOS Permissions -->
<edit-config file="*-Info.plist" mode="merge" target="NSBluetoothAlwaysUsageDescription">
  <string>Need Bluetooth access to connect to your glucose monitoring device</string>
</edit-config>
<edit-config file="*-Info.plist" mode="merge" target="NSBluetoothPeripheralUsageDescription">
  <string>Need Bluetooth access to connect to your glucose monitoring device</string>
</edit-config>
6. Build the UI to Interact with xdrip-js

Update src/app/home/home.page.ts (Ionic 4) or src/pages/home/home.ts (Ionic 3):

import { Component } from '@angular/core';
import { XdripService } from '../services/xdrip.service';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  public availableDevices: any[] = [];
  public currentReading: number | null = null;
  public isConnected = false;

  constructor(private xdripService: XdripService) {
    // Check for new glucose readings every second
    setInterval(() => {
      if (this.xdripService.glucoseUpdates.length > 0) {
        const latest = this.xdripService.glucoseUpdates.at(-1);
        this.currentReading = latest.glucose;
      }
    }, 1000);
  }

  async scanDevices() {
    this.availableDevices = await this.xdripService.scanForDevices();
  }

  async connectToDevice(device: any) {
    await this.xdripService.connectToDevice(device.id);
    this.isConnected = true;
  }

  disconnect() {
    this.xdripService.disconnectDevice();
    this.isConnected = false;
    this.currentReading = null;
  }
}

Then update the corresponding HTML file (home.page.html):

<ion-header>
  <ion-toolbar>
    <ion-title>Glucose Monitor</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content class="ion-padding">
  <ion-button 
    (click)="scanDevices()" 
    expand="block" 
    [disabled]="isConnected">
    Scan for Devices
  </ion-button>

  <ion-list *ngIf="availableDevices.length > 0 && !isConnected">
    <ion-item *ngFor="let device of availableDevices" (click)="connectToDevice(device)">
      <ion-label>
        <h2>{{ device.name || 'Unknown Device' }}</h2>
        <p>{{ device.id }}</p>
      </ion-label>
    </ion-item>
  </ion-list>

  <div *ngIf="isConnected" class="connected-state">
    <h3>Connected to Device</h3>
    <ion-button (click)="disconnect()" color="danger" expand="block">Disconnect</ion-button>
  </div>

  <div *ngIf="currentReading !== null" class="glucose-display">
    <h1>{{ currentReading }} mg/dL</h1>
    <p>Latest reading</p>
  </div>
</ion-content>
7. Troubleshooting Common Issues
  • Bluetooth Permission Errors: On Android 12+, add BLUETOOTH_SCAN and BLUETOOTH_CONNECT permissions to config.xml if you see access denied errors.
  • Ionic 3 Polyfill Issues: If you get "property 'includes' does not exist" errors, double-check your polyfills.ts entries.
  • Device Connection Drops: Some glucose monitors have short connection timeouts. Add reconnection logic in the deviceDisconnected event listener if needed.
  • xdrip-js Compatibility: Stick to the latest stable version of xdrip-js to avoid bugs with newer Ionic/Cordova versions.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:09:36