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?
To run the change detector manually: Inject ChangeDetectorRef service in the component. Use markForCheck in the subscription method to instruct Angular to check the component the next time change detectors run. On the ngOnDestroy() life cycle hook, unsubscribe from the observable.
Change detection is the process through which Angular checks to see whether your application state has changed, and if any DOM needs to be updated. At a high level, Angular walks your components from top to bottom, looking for changes.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With