我在Angular2中有一个组件,它正在改变我的service translate.service.ts中的“lang”类变量.在另一个组件中,我使用init上的翻译来获取一个dict.如果第一个组件稍后更改了服务语言,我想自动在第二个组件中提取dict.我怎么做?
第一部分:
setLang(lang) { this._translateService.setLang(lang); }
服务:
dict = { "en": {}}; lang = "en"; setLang(lang) { this.lang = lang; } getLang() { return this.dict; }
第二部分:
ngOnInit() { this.dict = this._translateService.getDict(); }
您应该在服务中使用EventEmitter:
export class LangService { langUpdated:EventEmitter = new EventEmitter(); setLang(lang) { this.lang = lang; this.langUpdated.emit(this.lang); } getLang() { return this.dict; } }
export class MyComponent { constructor(private _translateService:LangService) { } ngOnInit() { this._translateService.langUpdated.subscribe( (lang) => { this.dict = this._translateService.getDict(); } ); } }
有关详细信息,请参阅此问题
> Delegation: EventEmitter or Observable in Angular2
> Delegation: EventEmitter or Observable in Angular2
编辑
EventEmitter should only be used for emitting custom Events in components,and that we should use Rx for other observable/event scenarios.