2017-03-07 55 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 –

相关问题