Tips for using $apply and $digest in Angular 4 and IONIC 3?

I am currently working on developing an application using IONIC 3, but facing challenges with the view not refreshing properly.

During my experience with Angular 1X, I used to use $apply and $digest to resolve similar issues. How can I achieve the same in Angular 4?

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { BLE } from '@ionic-native/ble';

@Component({
  selector: 'page-led',
  templateUrl: 'led.html'
})
export class LEDPage {

  constructor(public navCtrl: NavController, private ble: BLE) {
    this['myCount'] = 0;
    this['valor'] = 0;
    this['messages'] = [];
    this['service_id'] = "19B10010-E8F2-537E-4F6C-D104768A1214";
    this.setMessage("Constructor: Begin!");
    this['ble'] = ble;
    this['ComandoTXT'] = "FIND BLYNK";
    this['targetDevice'] = {};
  }
  
  public Command(){
    if(this['ComandoTXT']==="FIND BLYNK") {
      this.findBlynk();
    }
    
    if(this['ComandoTXT']=== "CAMBIAR LED"){
      //this.txData();
      this.setMessage("CAMBIAR LED txData DISABLEd");
    }
  }
  
  public findBlynk(){
      this.setMessage("SCAN: Begin!");
      this['ComandoTXT'] = "Scanning...";

      let  ble = this['ble'];
      
      this.setMessage("SCAN: BLE ENABLE!");
      ble.enable();
      
      this.setMessage("SCAN: Setting Interval...");
      this['intervalHandle'] = setInterval(() => { // SET AN INTERVAL THAT RUNS EVERY 3 Seconds
        this.setMessage("INTERVAL: BLE SCAN...");
        //https://ionicframework.com/docs/native/ble/ 
        ble.scan([], 2 /*seconds (0) */).subscribe( data => { //DO SCAN DURING 1 SECOND
          this.setMessage("SCAN SUBSCRIBER: " + data['id'] + ' | ' + data['name'] + ' | ' + data['rssi']);
          if(data['name']=="Blynk"){
            this.setMessage("SCAN SUBSCRIBER: BLYNK FOUND! STOPPED SCANNING!");
            clearInterval(this["intervalHandle"]);
            this["targetDevice"] = data;
            this["ComandoTXT"] = "CAMBIAR LED";

            let idx = 0;
            while(idx<10000){
              this["test"] = idx;
              idx ++;
            }
          }
        });
      },2100);//END OF INTERVAL DEFINITION
    }  
  
  public setMessage(message){
    this['myCount'] ++;
    message = this['myCount'] + ':' + message;
    this['messages'].unshift(message);
  }

}
<ion-header>
  <ion-navbar>
    <ion-title>LED </ion-title>
    <button ion-button (click)="Command()">{{ComandoTXT}}</button>
  </ion-navbar>
</ion-header>
<ion-content padding>
  <p>LED Messages: ({{myCount}} | {{test}})</p>
  <hr />
  <p *ngFor="let message of messages">{{message}}</p>
</ion-content>

Answer №1

Initially, the challenge stemmed from my lack of knowledge on how to utilize the ApplicationRef object in Typescript.

To resolve this issue, I incorporated "

import { ApplicationRef } from '@angular/core'
" at line 4 within my .ts file. Subsequently, I injected it in the constructor as private "applicationRef : ApplicationRef" on line 28 and executed "this.applicationRef.tick();" towards the end of callbacks like on line 81.

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { BLE } from '@ionic-native/ble';
import { ApplicationRef } from '@angular/core'

@Component({
  selector: 'page-led',
  templateUrl: 'led.html'
})


export class LEDPage {

  /**
   * Constants that we will use around the controller
   */
  public constants  = {
      CMD_FIND_ANGU:"FIND ANGU",
      CMD_STOP_SCAN:"Scanning... (Click to Stop)",
      CMD_TOGGLE_LED:"CAMBIAR LED",
      ON:"ON",
      OFF:"OFF"
    };

  /**
   * Constructor for the controller. Everything begins here.
   */
  constructor(public navCtrl: NavController, private ble: BLE, private applicationRef : ApplicationRef ) {
    this['messages'] = [];
    this['value'] = "ON FIRST TIME";
    this['service_id'] = "19B10010-E8F2-537E-4F6C-D104768A1215";
    this['characteristic_id'] = "19B10011-E8F2-537E-4F6C-D104768A1215";
    this['ble'] = ble;
    this['ComandoTXT'] = this.constants.CMD_FIND_ANGU;
    this['targetDevice'] = {};
    this.setMessage("Constructor: Begin!");
    this["applicationRef"] = applicationRef;
  }
  
[Additional code remains unchanged]
  
}
<ion-header>
  <ion-navbar>
    <ion-title>LED </ion-title>
    <button ion-button (click)="Command()">{{ComandoTXT}}</button>
  </ion-navbar>
</ion-header>
<ion-content padding>
  <p>LED  Messages: ({{myCount}} | {{test}})</p>
  <hr />
  <p *ngFor="let message of messages">{{message}}</p>
</ion-content>

Answer №2

To accomplish this task, you can utilize the LifeCycle::tick() method. Refer to the code snippet below:

import {Component, LifeCycle, NgZone} from 'angular2/angular2'

@Component({
  selector: 'my-app',
  template: `
    <div>
      Hello world!!! Time: {{ time }}.
    </div>
  `
})
export class App {
  time: number = 0;

  constructor(lc: LifeCycle, zone: NgZone) {
    zone.runOutsideAngular(() => {
      setInterval(() => {
        this.time = Date.now();

        lc.tick(); // If you comment out this line, the "time" will stop updating
      }, 1000);
    })
  }
  doCheck() {
    console.log('check', Date.now());
  }
}

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

Using Generic Types in TypeScript for Conditional Logic

To better illustrate my goal, I will use code: Let's start with two classes: Shoe and Dress class Shoe { constructor(public size: number){} } class Dress { constructor(public style: string){} } I need a generic box that can hold either a ...

Tips for avoiding sending empty fields when using Angular's HttpClient.post method

Whenever I try to send data using the POST method to my Rest API in Angular, it ends up sending empty fields resulting in my database storing these empty values. I want to find a way to stop this from happening so that no empty fields are sent from Angula ...

Displaying server errors in an Angular componentIn this tutorial, we

As I work on creating a registration page, my focus has been on posting data to the server. I have successfully implemented client-side and server-side validation mechanisms. Managing client-side errors is straightforward using code such as *ngIf="(emailAd ...

What is the process for importing a function dynamically in a Next.js TypeScript environment?

Currently, I am utilizing a React modal library known as react-st-modal, and I am attempting to bring in a hook named useDialog. Unfortunately, my code is not functioning as expected and appears like this: const Dialog = dynamic<Function>( import(& ...

Issue encountered when attempting to access disk JSON data: 404 error code detected

I am attempting to retrieve JSON data from the disk using a service: import { Product } from './../models/Product'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { HttpClient } from &apo ...

Transitioning from ng-repeat filter to Typescript

As I migrate my project from AngularJS to modern Angular 8, one of the steps is converting JavaScript code to TypeScript. During this process, I encountered a challenging issue with the `ng-repeat` filter feature. Initially, my HTML template looked like t ...

Issue encountered while creating production build using Ionic

I've encountered a perplexing error that has me stumped. The error reared its head while attempting to build with --prod. Despite my efforts to fix it by updating dependencies, when I run ionic cordova build android --prod --verbose, the following er ...

Is there a way to modify CSS class names on-the-fly within an Angular project?

I am working with two CSS classes named as below: .icon_heart{ color: #bdbdbd; } .icon_heart_red{ color: #a6b7d4;; } Within my HTML code, I have incorporated a heart icon. <div class="icon_heart" *ngIf="showheartIcon"> ...

Communicating between different components in Angular 11 using a service to share data

In my Angular 11 project, componentB has multiple methods that need to be called from componentA. Although I am aware that transferring these methods to a service would be the proper solution, it requires extensive effort which I want to avoid for now. In ...

Positioning the Angular material menu items in the UI

Hey there! I'm looking to create a mat-menu that opens to the left. I found some code snippets on StackBlitz, check it out: https://stackblitz.com/edit/angular-material-menu-position-aside-6ab669?file=src/app/menu-overview-example.html The menu str ...

Customize stepper background color in Angular Material based on specific conditions

I am working on a project using Angular Material and I want to dynamically change the color of the stepper based on different states. For example: state: OK (should be green) state: REFUSED (should be red) Here is what I have done so far: <mat-horizo ...

Error encountered with Angular version 4: Unexpected token export

Upon starting the app with the command ng serve, I encountered an error in the console: VM1018:2297 Uncaught SyntaxError: Unexpected token export at eval (<anonymous>) at webpackJsonp.../../../../script-loader/addScript.js.mod ...

Guide to simulating Twilio with Jest and TypeScript to perform unit testing

Please assist me in mocking a Twilio service that sends messages using Jest to mock the service. Below is the code I am working with: import { SQSEvent } from "aws-lambda"; import { GetSecretValueResponse } from "aws-sdk/clients/secretsmanag ...

Resolving NestJS Custom Startup Dependencies

In my setup, I have a factory responsible for resolving redis connections: import {RedisClient} from "redis"; export const RedisProvider = { provide: 'RedisToken', useFactory: async () => { return new Promise((resolve, reject ...

lines stay unbroken in angular

I am encountering an issue when I execute the following code: DetailDisplayer(row) : String { let resultAsString = ""; console.log(row.metadata.questions.length); (row.metadata.questions.length != 0 )?resultAsString += "Questions ...

Showcasing a single object in an IONIC/Angular application using the ngIF directive

I am in need of assistance as I have encountered an issue. Essentially, I am fetching an object from an external API (Strapi) using the GET method, but when attempting to display it on Views with ngIF, it fails to show up. Below is the code snippet: word ...

The statement "import React from 'react'" is automatically removed by VS Code

When I need to remove unused modules that I no longer need, I frequently use shift + alt + o. This method has worked perfectly for me in the past when editing .tsx files. However, recently, VS Code seems to be removing the import React from 'react&ap ...

In my Angular application, the Authentication JWT is securely stored by Firebase within the Session Storage. Does this implementation pose any security risks

In order to enhance the user experience of our Angular app, we have integrated Firebase Authentication with Session Persistence. This ensures that users don't need to log in again every time they refresh the page. As part of this process, we store the ...

Asynchronous data binding in Angular 2

I'm trying to pass a value from my ImageDetail component to the ImageComment component as follows: ImageDetailHtml: <image-comment [photo]="photo"></image-comment> ImageCommentComponent: export class ImageCommentComponent { @Input(&a ...

Trigger on the cancellation or completion of a nested observable

I'm seeking a way to detect if an inner observable was not successfully completed (due to everyone unsubscribing) and then emit a value in that scenario. Something akin to defaultIfEmpty, but the current solution isn't effective. A trigger exis ...