Search code examples
angularangular2-services

How to detect variable change in Angular2


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?


Solution

  • 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.