0

How to make sure all components have access to same data ?

Problem

  • When components change data while others still use an old value.
  • When component refresh data it's refreshed locally by not for other components.

How to deal with this ? is theire a design pattern explaining how to centralise data source to handle this

user2080105
  • 1,642
  • 4
  • 18
  • 27
  • Possible duplicate of [How do I share data between components in Angular 2?](https://stackoverflow.com/questions/31026886/how-do-i-share-data-between-components-in-angular-2) – Bohdan Khodakivskyi Dec 07 '17 at 11:42

1 Answers1

0

The best way to share data between components is to use service.

As per official style guide it is not recommended to perform complex data manipulations inside components:

The component's responsibility is for the presentation and gathering of information for the view. It should not care how it gets the data, just that it knows who to ask for it. Separating the data services moves the logic on how to get it to the data service, and lets the component be simpler and more focused on the view.

If you still need to update data on the component level, you would need to do manual change detection checks. OnChanges lifecycle hook method is what you're looking for I believe.

  • I use services but I am asking for more strict standard or design patterns to assure data consistency, Example: get array from service, add element to this array in the component1, component 2 access the same array from the same service, since service is not notified about the new element added, component 2 have no idea about this element, how to handle this ? – user2080105 Dec 07 '17 at 12:36
  • That's exactly why I said that it's not recommended to perform complex data manipulations in components directly. In your case: it's better to create a standalone setter method for your service which will handle adding elements to an array of this service. Inside your component just call this method instead of modifying service's properties from components. – Bohdan Khodakivskyi Dec 07 '17 at 12:42
  • It's also important to note that you should provide your data service once in `AppModule` or `CoreModule` etc. depending on your file structure rather than each time in your components individually because it will create different instances thus it won't be able to share data. – Bohdan Khodakivskyi Dec 07 '17 at 12:45