2017-03-07 17 views
0

サービスからコンポーネントに更新された値を取得する方法を教えてください。以下では、ConnectValueからMasterComponentにshowValuesを取得しようとしています。角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

任意のコンポーネント

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

のための通知として使用EventEmitter

@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

に私はちょうど私のサービスからの変数を更新しようとしています

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

rxjsからSubjectを使用しています。これを行う簡単な方法はありますか? – NMNB

+0

これはEventEmitterで通知者として使用できるのは2つの基本的な方法です。もう1つはSubjectを使用してObservableです –

関連する問題