4

I have an angular2 app. There is a service which is used in many components. This service provides a static method (which can be used from outside the angular app to update the value:

class MyService {
    static _value: any;

    get value(): any {
        return MyService._value;
    }

    static updateValue(value: any): void {
        MyService._value = value;
    }
}

In my components I use the service and value likes this:

@Component({...})
class MyComponent {
    constructor(private myService: MyService) {}
    get formattedValue(): string {
        return 'the value is ' + String(this.myService.value)';
    }
}

The problem is, that when I call the static function window.MyServiceClass.updateValue(3), the change detection does not detect the change and the output value is still the old one.

My solution is currently to have a EventEmitter in my service, which can be subscribed by components depending on the value. The EventEmitter emits each time, the value is changed. The components subscribe to the EventEmitter in the ngOnInit() method, have the ChangeDetectorRef, call detectChanges() when the emitter emits and unsubscribe from it in the ngOnDestroy().

But I don't like this solution, because I have to subscribe and unsubscribe in each component and need the ChangeDetectorRef injected.

Is there a possibility to trigger a global change detection? So the service can trigger this detection when the value is updated?

Thanks in advance!

be-ndee
  • 1,153
  • 3
  • 13
  • 19

0 Answers0