How to detect a variable change in Angular2

I have the following configuration object that is installed before the constructor starts:

config: Object = {

    onSlideChangeEnd : function(slide:any) {

        this.currentSlideIndex = slide.activeIndex;
    }
};

I want to notify the service of the change, the problem is that the service is not yet available during configuration:

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

How can I notify the service of a change to this variable?

+3
source share
1 answer

Well, as intended to use Observables, this is actually not such a big problem, and it works pretty well. These are no more than a few lines.

Declare in some shared service a service that they share as such, for example, a service declared by the provider in this module, so that you do not get two instances of the same service. Add Subjectto this service a method to retrieve the value:

public configObservable = new Subject<number>();

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

config:

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

, :

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

-:

Plunker

@Input(), -, .

+14

Source: https://habr.com/ru/post/1695517/


All Articles