我有一个angular2应用程序。有许多组件使用的服务。此服务提供静态方法(可以在角度应用程序外部使用以更新值:
class MyService {
static _value: any;
get value(): any {
return MyService._value;
}
static updateValue(value: any): void {
MyService._value = value;
}
}
在我的组件中,我使用的服务和值都是这样的:
@Component({...})
class MyComponent {
constructor(private myService: MyService) {}
get formattedValue(): string {
return 'the value is ' + String(this.myService.value)';
}
}
问题是,当我调用静态函数window.MyServiceClass.updateValue(3)
时,更改检测不会检测到更改,输出值仍然是旧的。
我的解决方案目前在我的服务中有一个EventEmitter
,可以根据值按组件订阅。 EventEmitter
每次都会发出,值会发生变化。组件在EventEmitter
方法中订阅ngOnInit()
,拥有ChangeDetectorRef
,在发射器发出时调用detectChanges()
,并在ngOnDestroy()
中取消订阅。< / p>
但我不喜欢这个解决方案,因为我必须在每个组件中订阅和取消订阅,并且需要注入ChangeDetectorRef
。
是否有可能触发全局变更检测?那么服务可以在更新值时触发此检测吗?
提前致谢!