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

Error: The token 'export' in d3zoom is causing a syntax issue

I'm encountering issues with executing tests in Angular: ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export {default as zoom} from "./zoom.js"; ...

The mat-slide-toggle component does not recognize the checked binding

My angular app contains the mat-slide-toggle functionality. switchValue: {{ switch }} <br /> <mat-slide-toggle [checked]="switch" (toggleChange)="toggle()">Toggle me!</mat-slide-toggle> </div> This is how the ...

Minimize the quantity of data points displayed along the X-axis in a highcharts graph

After making an API call, I received data for a Highcharts graph consisting of an array of datetimes (in milliseconds) and corresponding values (yAxis). The data is fetched every 15 minutes and displayed on a mobile device. When viewing the data monthly, ...

What is the best way to customize a button component's className when importing it into another component?

Looking to customize a button based on the specific page it's imported on? Let's dive into my button component code: import React from "react"; import "./Button.css"; export interface Props { // List of props here } // Button component def ...

Accessing the Component Property from an Attribute Directive in Angular 2

Currently, I am in the process of creating filter components for a grid (Ag-Grid) and planning to use them in various locations. To make these filters accessible from different places, I am developing a wrapper for them. In particular, I am working on a fi ...

Looking to change the pagination arrow icons in Angular's mat-paginator to something different. Let's replace them with new icons

Looking to customize the arrows icons on an Angular mat-paginator for a unique design. For more information on mat-paginator, please see this link: https://material.angular.io/components/paginator/overview I attempted to locate a way to change the icon by ...

Utilize Typescript to inject types into a library

I have a code snippet that reads data from a JSON file and creates a type based on it, which is then used for further operations. import jsonData from './mydata.json' type CustomType = typeof jsonData .... This process ensures that the generate ...

What is the best way to globally incorporate tether or any other feature in my Meteor 1.3 TypeScript project?

I've been working hard to get my ng2-prototype up and running in a meteor1.3 environment. Previously, I was using webpack to build the prototype and utilized a provide plugin to make jQuery and Tether available during module building: plugins: [ ne ...

The challenge of migrating from Angular2 Rc4 to Rc5: dealing with traceur bug

Encountering 'traceur 404' error in console during the migration process of my angular cli project from Rc4 to Rc5 https://i.stack.imgur.com/j4SU1.png Referenced this article for guidance: app.module.ts import {NgModule} from '@angu ...

Modify the color of Material UI's Select Component's IconComponent

Currently in my project, I am utilizing MUI's Select Component with the LanguageIcon as the designated IconComponent. My goal is to change the color of this icon from black (default) to white, but I have been unsuccessful in my attempts. I attempte ...

What is causing the failure of the state to be inherited by the child component in this scenario (TypeScript/React/SPFX)?

For this scenario, I have a Parent class component called Dibf and a Child class component named Header. While I can successfully pass props from the Parent to the child, I am encountering difficulties when trying to pass state down by implementing the fo ...

Styling your Angular project with CSS

I have a folder called about which contains a file named about.component.css . I want the background-color to be set to aqua only for the page about.component.html. When I try setting the background-color in about.component.css like this: body { backg ...

What are the distinctions between manually and programmatically changing URLs in Angular 6?

My query pertains to differentiating navigation methods, specifically between clicking a button with [routerLink] and manually entering a URL in the browser's search bar. Update: I have a fixed menu on a certain page that appears as follows: <ul& ...

Enhancing Apollo Cache Updates using TypeScript null checks

Currently, I am utilizing apollo codgen to automatically generate types for my graphql queries in TypeScript. However, I have noticed that the generated types contain numerous instances of null values, leading to an abundance of if checks throughout my cod ...

How can I best declare a reactive variable without a value in Vue 3 using TypeScript?

Is there a way to initialize a reactive variable without assigning it a value initially? After trying various methods, I found that using null as the initial value doesn't seem to work: const workspaceReact = reactive(null) // incorrect! Cannot pass n ...

Can a substring within a string be customized by changing its color or converting it into a different HTML tag when it is defined as a string property?

Let's discuss a scenario where we have a React component that takes a string as a prop: interface MyProps { myInput: string; } export function MyComponent({ myInput }: MyProps) { ... return ( <div> {myInput} </div> ...

Access to the server has been restricted due to CORS policy blocking: No 'Access-Control-Allow-Origin'

I’m currently encountering an issue with displaying API content in Angular and I’m at a loss on how to troubleshoot it and move forward. At this moment, my main objective is to simply view the URL data on my interface. Does anyone have any insights or ...

Should Angular libraries be developed using Typescript or transpiled into JavaScript?

Currently, I am in the process of developing a library that will be available as an Angular module through npm. The library itself has been written using typescript. Everything was functioning perfectly up until Angular version 5.0.0, but after this update ...

Unidirectional data flow from the document object model to the variable within the

When working with Angular, there are multiple methods available for binding variables to DOM properties. You can utilize the `{{}}` syntax, `[property]=expression`, or implement two-way ngModel binding. One aspect that I have not yet discovered is how to ...

Combine Immer and NgRx reducer for improved state management

Upon analyzing redux and ngrx, it appears that immer is the preferred library for creating a copy of the state before storing it. In following the example provided by immer, I implemented the following code in my reducer: on(exampleActions.updateExample ...