2017-08-23 5 views
0

BLE検索APPを作成するためにNativeScriptおよびnativescript-bluetoothプラグインを使用しています。 デバイスの検索中にビューを更新する方法を理解できませんでした。 それはスキャン中にここに私のコードは、それは、NativeScript BLE - nativescript-bluetoothを使用してデバイスを検索中にインタフェースを更新します。

app.modules.ts

import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core"; 
import { NativeScriptModule } from "nativescript-angular/nativescript.module"; 

import { AppComponent } from "./app.component"; 

@NgModule({ 
    declarations: [AppComponent], 
    bootstrap: [AppComponent], 
    imports: [NativeScriptModule], 
    schemas: [NO_ERRORS_SCHEMA], 
}) 
export class AppModule {} 

app.component.ts

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

let ble = require("nativescript-bluetooth"); 

@Component({ 
    selector: "my-app", 
    styleUrls: ['app.css'], 
    templateUrl: "app.component.html" 
}) 
export class AppComponent { 
    log: string = ""; 


    startScanning() { 
     ble.startScanning({ 
      serviceUUIDs: [], 
      seconds: 5, 
      onDiscovered: (peripheral) => { 
       if (peripheral.name == "SWING") { 
        this.stopScanning(); 
        this.updateLog(`Device Name: ${peripheral.name}`); 
       } 
      } 
     }).then(() => { 
      this.updateLog("scanning completed"); 
     }, (err) => { 
      console.error(`Error on scanning: ${err}`); 
     }) 
    } 

    stopScanning() { 
     ble.stopScanning().then(() => { 
      this.updateLog("Stopped"); 
     }) 
    } 

    updateLog(message) { 
     console.log(message); 
     this.log += `\n${message}`; 
    } 
} 

app.component.html

<ActionBar title="My App"> 
</ActionBar> 
<StackLayout> 
    <Button class="btn btn-primary btn-active" id="appButton" text="Search Device" (tap)="startScanning()"></Button> 

    <TextView text="{{ log }}" style="height: 100%;background-color: #282a37;color: #fff;" editable="false"></TextView> 
</StackLayout> 

です5秒前にログをビューに更新しないで、ble.startScanningを終了します。 私はそれがBLEプラグインに関連していないと信じています。それはJavascript PromiseやNativeScriptの問題によく似ています。

ありがとうございます。

+0

この例ではRxJSを使用していません。 – paulpdaniels

+0

はい、@ paulpdanielsあなたは正しいです。私はRxJsではなくPromise/waitメソッドを意味しました。それを削除するためにコンテンツを更新しました。ありがとうございました –

+0

'updateLog'関数も共有してください。 –

答えて

0

コールバックはAngularのライフサイクルの外で実行されるため、Angularが更新を認識し(結果的にUIを更新するため)、少し蹴る必要があります。

これは、NgZoneの目的です。

// add 
constuctor(private zone: NgZone) {} 

// within 'onDiscovered', add 
this.zone.run(() => { 
    this.updateLog(`Device Name: ${peripheral.name}`); 
}) 
+0

ありがとう!私はNgZoneのことをする必要があることを知っていました!あなたは私の週を救った! –

関連する問題