In order to sync the data among difference components, I'm using a single service object, and some members variables of the service are assigned to the components local variables in the their ngOnInit callback.
With this approach, and changes to the data can be refreshed on the component view automatically, no need some kind of event subscription techniques.
But I'm not sure if it is the right way for components to interact, or would there be any problem in the future. Would someone please provide comments?
This is a valid way to share properties. Services in Angular are simply singletons within their given provider scope. However, I would say that this is does not closely match a canonical way to share properties for two main reasons:
ChangeDetectionStrategy.OnPush
strategy is usedUsing Observable
objects in the service could help mitigate both of these issues. For example, using BehaviorSubject
objects would allow components to change the value provided by the service (via BehaviorSubject.prototype.next(value)
) and to subscribe to the service-proivded value to efficiently perform change detection (done simply through the async
pipe when in a template). BehaviorSubject
objects also conveniently have the getValue()
function to synchronously get the existing property value if needed.
That being said, using Observable
fields does have an additional cost and its benefit depends on your situation. I suggest sticking with the KISS principle and keep what you have until you'd actually benefit from doing anything more complex.