Skip to content

Instantly share code, notes, and snippets.

@anantl05
Last active September 21, 2019 06:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anantl05/425fe60b43215b1a460916df34ca4e2c to your computer and use it in GitHub Desktop.
Save anantl05/425fe60b43215b1a460916df34ca4e2c to your computer and use it in GitHub Desktop.
import { Component, OnInit, ViewChild, ElementRef, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { IMqttMessage, MqttService } from 'ngx-mqtt';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
private subscription: Subscription;
topicname: any;
msg: any;
isConnected: boolean = false;
@ViewChild('msglog', { static: true }) msglog: ElementRef;
constructor(private _mqttService: MqttService) { }
ngOnInit(): void {}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
subscribeNewTopic(): void {
console.log('inside subscribe new topic')
this.subscription = this._mqttService.observe(this.topicname).subscribe((message: IMqttMessage) => {
this.msg = message;
console.log('msg: ', message)
this.logMsg('Message: ' + message.payload.toString() + '<br> for topic: ' + message.topic);
});
this.logMsg('subscribed to topic: ' + this.topicname)
}
sendmsg(): void {
// use unsafe publish for non-ssl websockets
this._mqttService.unsafePublish(this.topicname, this.msg, { qos: 1, retain: true })
this.msg = ''
}
logMsg(message): void {
this.msglog.nativeElement.innerHTML += '<br><hr>' + message;
}
clear(): void {
this.msglog.nativeElement.innerHTML = '';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment