angular7使用mqtt

1.npm install ngx-mqtt --save

2.创建一个mt.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import {IMqttMessage,MqttModule,MqttService} from 'ngx-mqtt';

export const MQTT_SERVICE_OPTIONS = {
  hostname: '',
  port: 9001,
  path: '/mqtt',
  username:'',
  password:''
};


@NgModule({
  declarations: [],
  imports: [
    CommonModule,
      MqttModule.forRoot(MQTT_SERVICE_OPTIONS)
  ]
})
export class MtModule { }

3.在app.module.ts中引入

4.在使用的ts文件

import {Subscription} from 'rxjs';
import {IMqttMessage, MqttService} from 'ngx-mqtt';

private subscription: Subscription;
public message: string; //访问topic拿到的值

constructor(private _mqttService: MqttService) {
        this.subscription = this._mqttService.observe('topic')
            .subscribe((message: IMqttMessage) => {
            this.message = message.payload.toString();
        });
    }

 

你可能感兴趣的:(Angular,mqtt)