Angular 2如何从服务到组件获取最新的更新值

时间:2017-03-07 12:34:49

标签: angular

如何从服务到组件获取更新值。下面我试图将ConnectValues从ConnectService转换为MasterComponent。

export class MasterComponent{
public showValue:string;
constructor(public connectService: ConnectService, public _router: Router){
if(localStorage.getItem("clientStatus")=='connected'){
this.showValue = this.connectService.showValues;
    console.log("MasterComponent",this.showValue);
}
}

从以下服务我想更新组件。

export class ConnectService{
  public showValues: string;
constructor(){
}
recvNotify(m) {
//getting value
buttonName = innervalue;
                console.log("ELSEinnervalue",buttonName);
                switch (buttonName) {
                    case "0x01010000":
                        console.log('showValue==1');

                        this.showValues = "1";
                    break;
                    case "0x01020000":
                        console.log('showValue==2');
                        this.showValues = "2";   
                        break;
                    default:
                        console.log('showValue==3');
                         this.showValues = "3";  
                    }
             }
}

1 个答案:

答案 0 :(得分:0)

使用EventEmitter作为任何组件的通知程序

import { EventEmitter, Injectable } from "@angular/core";
@Injectable()
export class SharedService {
  private emitter: EventEmitter<any>;
  constructor() {
    this.emitter = new EventEmitter<any>();
  }
  getEmitter(): EventEmitter<any> {
    return this.emitter;
  }
  emit(data: any): void {
    this.emitter.emit(data);
  }
}

并订阅此类组件中的事件并更新任何内容

@Component({
 template: ''
})
export class MyComponent{
 constructor(private emitter: SharedService){
   this.emitter.getEmitter().subscribe(e => {
    // do stuff here
   });
 }
}

不要忘记将其添加到NgModule并将其用作服务。第二种方法是使用Subject

中的rxjs
import { Injectable } from "@angular/core";
import { Subject, Observable } from "rxjs";
@Injectable()
export class SharedService {
  public notifier: Observable<any>;
  public source: Subject<any> = new Subject<any>;
  constructor(){
   this.notifier = this.source.asObservable();
  }

  emit(data: any): void {
    this.source.next(data);
  }
}

然后在组件中

export class MyComponent{
 constructor(private service: SharedService){
   this.service.notifier.subscribe(e => {
    // do stuff here
   });
 }
}