How to detect variable change in Angular2

Yuvals picture Yuvals · Jan 28, 2017 · Viewed 50.6k times · Source

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?

Answer

AJT82 picture AJT82 · Jan 29, 2017

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.