如何在多个组件中注入来自一个服务的实时数据,角度为5

时间:2018-01-25 09:37:42

标签: angular typescript

我从客户端获取实时数据消息,并希望在2个视图组件中同时显示数据。
Mi的想法是使用抽象类或接口。 这是我的客户服务,我从中获取数据:

import { Injectable } from '@angular/core';
import {Paho} from '../../../../../node_modules/ng2-mqtt/mqttws31';
import 'rxjs/add/observable/interval';
import {AddMqttformToClientService} from '../../add-live-data-button/forms/mqttform/add-mqttform-to-client.service';
import {AbstractClassService} from '../abstract-class.service';

@Injectable()
export class MqttProviderService extends AbstractClassService {

 // Create a client instance
  client: any;

  public constructor(private getformvaules: AddMqttformToClientService) {
   super();
    console.log("Generate Service");
    this.getformvaules.componentMethodCalled$.subscribe(
      () => {
        this.client = new Paho.MQTT.Client(this.getformvaules.addmqtt.addmqttadress, Number(this.getformvaules.addmqtt.addmqttport), this.getformvaules.addmqtt.addmqttusername);
        this.onConnectionLost();
        // connect the client
        this.client.connect({
          onSuccess: this.onConnected.bind(this)
        });
        //this.onDisconnect();
      }
    );
  }

  // called when the client connects
  onConnected() {
    let that = this;
    console.log('Connected');
    // this.client.subscribe('node/m1/temperature');
    // this.client.subscribe('node/m1/humidity');
    this.client.subscribe(this.getformvaules.addmqtt.addmqtttopicfilter);
    this.client.onMessageArrived = function(message) {
      that.onMessage(message.payloadString);
    };
  };


  // called when a message arrives
  public onMessage(msg: string) {
  }


  onDisconnect () {}

  // called when the client loses its connection
  onConnectionLost() {}

}


带有onMessage方法的抽象类,我想在组件1和组件2中注入。

import { Injectable } from '@angular/core';

@Injectable()
export abstract class AbstractClassService {

  public onMessage(msg: string): void {
  }
}


组件1:

import { Component, OnInit, Inject } from '@angular/core';
import {AbstractClassService} from '../../protocols/abstract-class.service';
import {MqttProviderService} from '../../protocols/mqtt/mqtt-provider.service';

    @Component({
      selector: 'app-gauge',
      templateUrl: './gauge.component.html',
      providers: [{
        provide: AbstractClassService,
        useClass: MqttProviderService
      }
      ],
      styleUrls: ['./gauge.component.css']
    })
    export class GaugeComponent  {

      data = [
        {
          name: '',
          value: ''
        }
      ];


      constructor(private abstractclassService: AbstractClassService ) {
        this.abstractclassService.onMessage = (msg: string) => {
          this.data = [{name: 'test', value: msg}];

      };
}


组件2

    import { Component, OnInit, Inject } from '@angular/core';
    import {AbstractClassService} from '../../protocols/abstract-class.service';
    import {MqttProviderService} from '../../protocols/mqtt/mqtt-provider.service';

    @Component({
      selector: 'app-gauge1',
      templateUrl: './gauge1.component.html',
      providers: [{
        provide: AbstractClassService,
        useClass: MqttProviderService
      }
      ],
      styleUrls: ['./gauge1.component.css']
    })
    export class GaugeComponent  {

      data = [
        {
          name: '',
          series: []
        },
      ];


      constructor(private abstractclassService: AbstractClassService ) {
        this.abstractclassService.onMessage = (msg: string) => {
               this.data1[0].series.push({ 'value': msg, 'name': String( new Date().getSeconds())});

      this.data = this.data.slice();

      };
}


目前我正在获取一个视图的数据!取决于在视图组件中将哪个组件命名为second:

<app-gauge></app-gauge> 
<app-gauge1></app-gauge1>

1 个答案:

答案 0 :(得分:0)

  1. 您正在组件中注入不同的服务实例。这是因为您在两个提供程序元数据字段中调用该服务。您应该只使用一个来允许您的组件共享相同的数据。
  2. 当我必须分享实时数据时,我就是这样做的:
  3. 为MyService:

    @Injectable()
    export class MqttProviderService {
      dataSubject: ReplaySubject<any>;
      data$: Observable<any>;
    
      constructor() {
       this.dataSubject = new ReplaySubject<any>();
       this.data$ = this.dataSubject.asObservable();
       methodToGetMyData();
      }
    
      methodToGetMyData() {
        //http call
        .subscribe((response: any) => this.dataSubject.next(response));
      }
    }
    

    使用此配置,您可以从模板访问实时数据:

    <span>myService.data$ | async</span> 
    

    在你的组件中你只需要在构造函数中注入服务:

    constructor(public myService: MqttProviderService) {}
    

    最后一点,请确保您在包含组件的模块的providers字段中提供服务。