Search code examples
angularangular2-services

Any drawbacks in sharing service class's member variables across components in Angular2?


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?


Solution

  • 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:

    1. The component values can be changed without the changes being reflected in the service
    2. Change detection will not be processed if the value reference within the service changes
      • As a side note on this, change detection will also not be processed on object mutation if the more efficient ChangeDetectionStrategy.OnPush strategy is used

    Using 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.