Enhance the user experience with NativeScript BLE by updating the interface in real-time during the device search process using

Currently, I am using the NativeScript framework along with the nativescript-bluetooth plugin to develop a BLE searching application. However, I am facing a challenge in updating the view while the device is being searched for. Below is the relevant code snippet:

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>

Even though it is expected to display real-time updates in the log while scanning, there seems to be a delay of 5 seconds before it actually reflects the changes due to the completion of ble.startScanning. This issue might not be directly related to the BLE plugin but rather could point towards Javascript Promise and NativeScript peculiarities.

Your feedback would be highly appreciated.

Answer №1

When the onDiscovered callback is triggered outside of Angular's lifecycle, it is necessary to notify Angular of any changes in order for the UI to be updated accordingly.

This is where NgZone comes into play.

// Add this line to the constructor
constructor(private zone: NgZone) {}

// Inside the 'onDiscovered' function, include this code snippet
this.zone.run(() => {
  this.updateLog(`Device Name: ${peripheral.name}`);
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring Real-Time Typescript Validation in Next.JS

Checking for TypeScript errors in Next.JS can only be done with npm run build (or yarn build). Unfortunately, running npm run dev won't display TypeScript errors, which is quite inconvenient as it would be better to have them visible in the Terminal ...

What are some effective methods for resetting a state in @ngrx/store?

Lately, I've been grappling with a problem that's been on my mind for the past few days. Our team is developing an Angular 2 application, and my task involves creating a wizard for users to complete a form. I've successfully set up the dat ...

What could be causing my asynchronous code to malfunction unless I explicitly log the promise?

My asynchronous code works fine locally when interacting with a MongoDB database, but issues arise when connecting to MongoDb Atlas. Strangely, my code seems to only work properly if I console.log the promise, which is confusing. Without the console.log st ...

Transform an AngularJS 1.x filter into AngularJS 2.0 pipes

I am looking for assistance in converting an Angular 1.x filter to Angular 2.0 pipes. Below is the code snippet for the Angular JS 1.x filter: $scope.selectname1={}; $scope.selectname2={}; $scope.selectname3={}; $scope.filter1 = fun ...

Interactive website built on Angular 16 offering advanced search and result display functionalities, along with options to edit and update data

Seeking guidance from experienced Angular developers as I am relatively new to the framework. Any tips or advice would be greatly appreciated. Project Overview: Front-end development using Angular, minimal focus on Back-end (C#) for now. https://i.sstati ...

Having trouble reaching pages through nginx server

When trying to load intermediate pages in my angular application by typing the URL each time like the examples below: http://localhost:port/Myproject/test1 (Default Page) http://localhost:port/Myproject/test2 http://localhost:port/Myproject/test3 I am ...

User interface designed for objects containing multiple keys of the same data type along with a distinct key

I have a question that relates to this topic: TypeScript: How to create an interface for an object with many keys of the same type and values of the same type?. My goal is to define an interface for an object that can have multiple optional keys, all of t ...

Is there a feature in Angular similar to Vue.js's "computed property" functionality?

After mastering Vue.js, I recently dove into Angular 4 for a new project. I've found that most things in Angular are quite similar to Vue, with the notable exception of "Computed Property". In Vue, I could easily create a computed property that would ...

Swapping out file in the Node_Modules directory

Recently, I needed to make changes to a file in the node modules directory. However, these modifications were being overwritten every time I ran npm install. Is there a way for me to keep this modified file in my local src folder and have it replace the on ...

What could be the reason for the absence of Mock Service Worker in a React project that has Typescript enabled?

After attempting to integrate Mock Service Worker into my React project with Typescript support, I encountered errors when running the npm install msw --save-dev command. The terminal displayed the following messages: PS F:\Programming\React Prac ...

Angular Filtering: Enhancing User Search Experience [Part 2]

When attempting to import the 'CommonModule', I encountered the same error message. However, when trying to write "of" between car and cars, it highlights the word filter as an error and displays: No pipe found with name 'filter'. I am ...

What is the process for utilizing a Typescript Unit Test to test Typescript code within Visual Studio?

Currently, I am facing an issue while writing a unit test in Typescript to check a Typescript class. The problem arises when the test is executed as it is unable to recognize the class. To provide some context, my setup includes Typescript (1.4) with Node ...

Deploying code from an S3 bucket to CodeCommit using AWS CDK

During the implementation of my CDK Stack, I encountered an issue when creating a Bucket, uploading files to it, and then creating a CodeCommit repository to store those files. Everything was going smoothly until I tried to create a new codecommit.CfnRepos ...

Develop a component library for Angular 2 without incorporating inline styles

I recently came across an interesting article about developing an Angular 2 component library that utilizes inline styles. Is there a method to create a library in Angular 2 without relying on inline styles? I also stumbled upon another resource, but it d ...

Assessing functionality in Angular8 by testing a function that accesses an array from a service

I have a function that I want to test along with the current test setup: canShowIt() { let showit = false; const profils = this.requestsService.userProfil; showit = profils.some((profil) => profil.id === this.profileDetail.id); return showit; ...

npm-bundle encounters an issue with Error: ENOENT when it cannot find the file or directory specified as 'package.json'

npm-bundle is throwing an error that says Error: ENOENT: no such file or directory, open 'package.json' in my NodeJs project. It works fine if I manually create test.js and package.json, then run npm install followed by npm-bundle. However, when ...

The NG8002 error has occurred, as it is not possible to connect to 'matDatepicker' because it is not a recognized attribute of 'input'

I've come across an issue while working on my Angular 15 application with Angular Material. I'm trying to incorporate a date picker, but after adding the code snippet below, I encountered an error. <mat-form-field appearance="outline" ...

Generic Typescript with keys that are of generic type and values that are of string

Here is the structure of my interface: interface Table<T> { data: T[]; tableConfig: TableConfig<T>; } interface TableConfig<T> { fieldNames: Array<keyof T>; idName: keyof T; } I have determined that whenever I use ...

The parent view in AngularJs navbar should remain active when any child view is currently active

My goal is to have the first view based on some sub-views while the main view remains abstract and only redirects to the first sub-view. I have implemented two nav bars for navigation - one for normal views and another specifically for navigating within th ...

Setting the height of a rich HTML editor component can be achieved in a few simple

Seeking guidance regarding adjusting the height of the editing area while using Quill, the rich html editor in my angular component. I am currently utilizing angular-7, bootstrap, and font-awesome, all at their latest versions. Despite thorough research, ...