ngx-gauge doesn't show the received data - javascript

I am developing a page that shows real-time data from a server. Now i'm testing it with some mqtt client websocket (like hivemq). The value itself that i receive is showed in the chrome console,but i'm trying to make this value graphical with NGX-GAUGE.
The ngx-gauge is showed correctly in the page,and if i put in "gaugeValue" a standard number it works (also with a Math.Random), but if i take a value from a MQTT broker,it just doesn't do anything
when i try to get the value from an MQTT broker, the value and green line of the ngx-gauge (which should increase/decrease in real time) doesn't do anything
import { Component, OnInit } from '#angular/core';
import { Paho } from 'ng2-mqtt/mqttws31';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
valore:String;
gaugeType = "semi";
gaugeValue=this.valore;
gaugeLabel = "Valore";
gaugeAppendText = "km/hr";s
animate=true;
duration=1500;
private client;
mqttbroker = 'broker.mqttdashboard.com';
ngOnInit() {
this.client = new Paho.MQTT.Client(this.mqttbroker, Number(8000), 'client1');
this.client.onMessageArrived=this.onMessageArrived.bind(this);
this.client.onConnectionLost=this.onConnectionLost.bind(this);
this.client.connect({onSuccess: this.onConnect.bind(this)});
}
onConnect() {
console.log('onConnect');
this.client.subscribe('testtopic/40/xxx');
}
onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log('onConnectionLost:' + responseObject.errorMessage);
}
}
onMessageArrived(message) {
console.log('onMessageArrived: ' + message.destinationName + ': ' + message.payloadString);
if (message.destinationName.indexOf('xxx') !== -1) {
this.valore = (message.payloadString);
}
}
}
It should simply show the value,with the line respondig in real time with that value

I also faced the same issue but I solved it after writing code by this way :
gaugeValue= 0; //define minimum value in export
this.gaugeValue= (message.payloadString); // intead of "this.valore" use this.gaugeValue
Please refer screenshot 1 & 2 for more understandings;
I used _thoughput_gaugeValue for defining
same _thoughput_gaugeValue is used as this._thoughput_gaugeValue for getting data. Do not declare _thoughput_gaugeValue:any

Related

Detect when a programmatically opened tab is closed by the user

I'm making a webapp with Angular 11 that uses the msgraph API to upload files to onedrive/sharepoint and then open the file in the Office online editor. This part is simple enough. I Also need to get the file back when the user is done with it. The requirement is that when the user closes the editor-tab I need to be notified of it, so I can download the file and delete it from onedrive/sharepoint.
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-test-page',
templateUrl: './test-page.component.html',
styleUrls: ['./test-page.component.scss']
})
export class TestPageComponent implements OnInit {
constructor() { }
winGoogle!: Window | null;
interval!: NodeJS.Timeout;
ngOnInit(): void {
this.interval = setInterval(this.detectClose, 1000);
}
openWin () {
this.winGoogle = window.open('http://google.com', '_blank');
}
closeWin () {
if(this.winGoogle) {
this.winGoogle.close();
}
}
detectClose() {
//detect if the tab is closed by the user ( not from code ) and remove the interval
clearInterval(this.interval)
}
}
I tried to look at the value of the "handler" (this.winGoogle), but its undefined at all times.
Does anyone know how can I achieve it or is it at all possible?
Seems like it can't be done without writing a browser extension.

The URL to Web Worker script is not found with Angular 7+

Iยดm testing Web Workers and combining them with Angular 7+
This is my app.component.html
<div>
<input type="text" name="lat" placeholder="Latitude" #lat (input)="updateMap( lat )">
<input type="text" name="lng" placeholder="Longitude" #lng (input)="updateMap( lng )">
</div>
This is my app.component.ts
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'mapa';
coords: any = {lat: 0, lng: 0};
worker: Worker;
ngOnInit() {
this.worker = new Worker( './app.component.worker.js' );
}
updateMap( selector: any ) {
const key = selector.getAttribute('name');
const value = Number(selector.value);
this.coords[ key ] = value;
this.worker.postMessage( this.coords );
}
}
This is my Webworker definition app.component.worker.js
onmessage = ( e ) => {
console.log( e );
};
All the files are at the same level.
project
-e2e
-node_modules
-src
-app
-app-routing.module.ts
-app.component.css
-app.component.html
-app.component.ts
-app.component.worker.js
-lot of files
-lot of files
When the local server runs, appears this message
GET http://localhost:4200/app.component.worker.js 404 (Not Found)
I tried to set as relative path
'./src/app/app.component.worker.js'
But stills not working
What is wrong with my code?
Does exists a best way to do all with Typescript?
I was also facing same issue with this code
const worker = new Worker('./web-worker/messenger.worker');
Change to
const worker = new Worker('./web-worker/messenger.worker', { type: `module` });
After this I am not getting this issue with web worker.
I am using this code on Angular 8.
Do not forget to run: ng generate web-worker
And then restart the angular serve , if not ,it will not compile your worker file into webpack.
For me it just worked by putting the path src/app/web-worker/messenger.worker.
Then try the following:
const worker = new Worker('src/app/web-worker/messenger.worker', { type: `module` });

Angular 2/4 two way data binding does not work in observable

Hi, I use a third party library simple-peer which I did declared declare var SimplePeer: any; in angular 4 , than the all logic of that is warped in navigator.n.mediaDevices.getUserMedia() (asking user for video/audio permission) which is asynchronous function and the problem is that SimplePeer returns some data that I need to use in my html but I can't output the data in my html only with console.log() , here is the code app.component.html:
<input type="text" [(ngModel)]="targetpeer">
<button (click)="connect()">Connect</button>
<button (click)="message()">Send Message</button>
<p>{{texttoken}}</p>
<video #myVideo></video>
ignore the video thing, everything works except that the {{texttoken}} is not updated, it displays the same initial dummy data that I set in my app.component.ts:
import { Component, OnInit, ViewChild } from '#angular/core';
import { Subject } from 'rxjs/Subject';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
#ViewChild('myVideo') myVideo:any;
texttoken :any = 'initial dummy value';
targetpeer: any;
peer: any;
n = <any>navigator;
ngOnInit() {
let video = this.myVideo.nativeElement;
let peerx: any;
let onJSTokenChange = new Subject(); // create new observable to obsere any changes to assign a value to texttoken
onJSTokenChange.subscribe((value)=>{
this.texttoken = value;
console.log(this.texttoken);
});
this.n.getUserMedia = (this.n.getUserMedia || this.n.webkitGetUserMedia || this.n.mozGetUserMedia || this.n.msGetUserMedia);
this.n.mediaDevices.getUserMedia({video:true, audio:true}).then( function(stream) {
peerx = new SimplePeer ({
initiator: location.hash === '#init',
trickle: false,
stream:stream
})
peerx.on('signal', function(data) {
console.log(JSON.stringify(data));
// here I pass that data to the observable
onJSTokenChange.next(JSON.stringify(data));
this.targetpeer = data;
})
peerx.on('data', function(data) {
console.log('Recieved message:' + data);
})
peerx.on('stream', function(stream) {
video.src = URL.createObjectURL(stream);
video.play();
})
}, function(err){
console.log('Failed to get stream', err);
});
}
connect() {
this.peer.signal(JSON.parse(this.targetpeer));
}
message() {
this.peer.send('Hello world');
}
}
here you can see that I assigned the dummy data to my texttoken , than I create an observable onJSTokenChange to track if something changes to assign a value to texttoken , this observable gets data from peerx.on('signal' code when ever it executes and then the onJSTokenChange.subscribe gets that data and console.log() the data which works as expected however the the.texttoken receives the value as well but it does not do the two-way binding and does not update <p>{{texttoken}}</p> even though I console.log() it and it returns the correct value , please help been trying to figure it out the whole day :(
I just imported ChangeDetectorRef from angular/core and injected
constructor(private detector:ChangeDetectorRef){}
used it in my
onJSTokenChange.subscribe((value)=>{
this.texttoken = value;
this.detector.detectChanges();
});
and it worked, thanks to #AJT_82 and #LLai

On calling JavaScript file from Angular 2 project

I had written a calendar control in jQuery that I wanted to use in an Angular 2 project.
I've learned from other answers on this topic that I can use jQuery's getScript() API to call into external JavaScript files.
My calendar.component.ts looks like this:
import { Component, OnInit, AfterViewInit } from '#angular/core';
import { Auth } from '../auth.service';
declare var $:any;
declare var CustomCal:any;
#Component({
selector: 'app-calendar',
templateUrl: './calendar.component.html',
styleUrls: ['./calendar.component.css']
})
export class CalendarComponent implements OnInit {
private year : number;
myCal : any;
constructor(private auth : Auth) {
}
ngOnInit() {
}
ngAfterViewInit() {
this.year = 2017;
$.getScript('./app/calendar/zapCalendar.js', function(){
console.log("got call'd back");
this.myCal = new CustomCal(2017);
});
}
}
I get the console message "got call'd back", then an error message stating that CustomCal is not defined.
My CustomCal class is defined in zapCalendar.js as follows:
class CustomCal
{
constructor(nYear) {
this._mouseDown = false;
this._mouseDrag = false;
this._lastItem = 0;
this._nYear = nYear;
this.CreateCalendarFrame();
this.AddEventHandlers(this);
}
...
}
I've tried export'ing the class in the zapCalendar.js file, and also tried adding the following to the zapCalendar.js file:
$( function() {
var myCal = new CustomCal(2017);
});
What am I missing here?
Update:
I've just replaced this (in zapCalendar.js)
$( function() {
var myCal = new CustomCal(2017);
});
with this:
var x = new CustomCal(2017);
And now the calendar is rendering correctly. But I'd like (if possible) to get a reference to the calendar in my typescript. Is this possible?
$.getScript('./app/calendar/zapCalendar.js', function(){
console.log("got call'd back");
this.myCal = new CustomCal(2017);
});
The inner function here will not have the same this reference because it won't be called bound to your object. Since you're using TypeScript, you can just use an arrow function to change this behavior.
$.getScript('./app/calendar/zapCalendar.js', () => {
console.log("got call'd back");
this.myCal = new CustomCal(2017);
});
you need to export class then import it in your component
import {CustomCal} from "./app/calendar/zapCalendar";

How can check offline and online in angular

I have been getting an error from the service call when browse is in offline mode. How can check off-line mode and want to block my service call when the browser is the offline mode?
I suggest you to use Offline.js
they have templates and other stuff to work with .
you can check out their documentation and see how it works .
it gets you the current state of the connection by returning the "up" or "down" result , or you can bind and event to it and use it across you'r application .
this is what they say about their library :
Offline.js is a library to automatically alert your users when they've lost internet connectivity, like Gmail.
It captures AJAX requests which were made while the connection was down, and remakes them when it's back up, so your app reacts perfectly.
It has a number of beautiful themes and requires no configuration.
good luck and have fun.
Check for navigator.onLineand based on this value decide whether to send request or not.
if (navigator.onLine) {
$http.get('url').success(function() {});
}
else {
// no req
}
Angular way:
Use $q service - A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing. https://docs.angularjs.org/api/ng/service/$q
The best way that I would know would be to intercept the HTTP handler, if its a 401 / 501/ etc. then to handle it according
angular.module('myApp', ['myApp.services'],
function ($httpProvider) {
var interceptor = ['$rootScope', '$q', function ($rootScope, $q) {
function success(response) {
return response;
}
function error(response) {
var status = response.status; // error code
if ((status >= 400) && (status < 500)) {
$rootScope.broadcast("AuthError", status);
return;
}
if ( (status >= 500) && (status < 600) ) {
$rootScope.broadcast("ServerError", status);
return;
}
// otherwise
return $q.reject(response);
}
return function (promise) {
return promise.then(success, error);
}
}];
$httpProvider.responseInterceptors.push(interceptor);
then in your code that listens for the on of, just add in
$rootScope.$on("ServerError", someServerErrorFunction);
Source: How to detect when online/offline status changes
Online/offline detection cannot be 100% accurately decided because network status can vary for a number of reasons.
Still, if you want an implementation of the same with Angular+NGRX, You can find more details here.
https://hackernoon.com/using-angular-to-detect-network-connection-status-onlineoffline
import { Component, OnDestroy, OnInit, VERSION } from '#angular/core';
import { fromEvent, merge, of, Subscription } from 'rxjs';
import { map } from 'rxjs/operators';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
networkStatus: boolean = false;
networkStatus$: Subscription = Subscription.EMPTY;
constructor() {}
ngOnInit(): void {
this.checkNetworkStatus();
}
ngOnDestroy(): void {
this.networkStatus$.unsubscribe();
}
checkNetworkStatus() {
this.networkStatus = navigator.onLine;
this.networkStatus$ = merge(
of(null),
fromEvent(window, 'online'),
fromEvent(window, 'offline')
)
.pipe(map(() => navigator.onLine))
.subscribe(status => {
console.log('status', status);
this.networkStatus = status;
});
}
}
You can see the demo here.
or check the code here
Happy coding!!! ๐ŸŽ‰๐ŸŽ‰๐ŸŽ‰

Categories

Resources