2017-03-07 71 views
0

如何從服務獲取組件更新值。下面我試圖從ConnectService獲取showValues到MasterComponent。Angular 2如何從服務獲取組件的最新更新值

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"; 
        } 
      } 
} 

回答

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,並用它就像服務一樣。第二種方式是在組件

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

我想剛剛更新從我服務的變量使用Subjectrxjs

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); } } 

然後。是否有任何簡單的方法來做到這一點 – NMNB

+0

這是基本的方式,只有兩件事可以用作通知者,是EventEmitter,第二種是使用Subject的Observable –

相關問題