How to detect variable change in Angular2

廉价感情. 提交于 2019-12-18 11:55:56

问题


I have the following config object which is set before the constructor is running:

config: Object = {
     onSlideChangeEnd : function(slide:any) {
          this.currentSlideIndex = slide.activeIndex;
     }
};

I want to notify a service about the change, the problem is that the service is not available yet when the configuration is set:

 constructor(private user: UserService,
             private layout: LayoutService) {
 }

How can I notify the service on this variable change?


回答1:


Well, as suggested use Observables, this is not really such a big hassle and it works quite well. It's not more than a few lines actually.

Declare in some common service, a service that they share as same, e.g a service declared as provider in that module, so that you do not end up with two instances of the same service. Add a Subject to that service and a method to emit value:

public configObservable = new Subject<number>();

emitConfig(val) {
  this.configObservable.next(val);
}

And in the component you need to set the config:

emit(val) { // your value you want to emit
  this.myService.emitConfig(val);
}

And then subscribe to the value where you need it:

constructor(private myService: MyService) {
  this.myService.configObservable.subscribe(value => {
    this.value = value;
  })
}

Working plunker with above code in a parent-child interaction:

Plunker

As to your comment about @Input(), that works well when a parent component-child interaction, so that wouldn't really work for you in this case.



来源:https://stackoverflow.com/questions/41915625/how-to-detect-variable-change-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!