Skip to main content

Front-End Development

Different Methods to Share Data Between Components in Angular – Part 2

Keyboard with search bar

Welcome back to different methods to share data between components in Angular.  In this post, we’ll continue with the remaining ways to share data in Angular components.

3. Sharing data using Routing Parameters or Query Parameters.

Angular’s routing module allows for passing data between components by utilizing route parameters.
Example:
Route Conf

Route Parent

We can pass data through the URL and retrieve it in the target component using the ActivatedRoute module.

4. Sharing data using State Management with Reactive Extensions (RxJS).

When dealing with complex data sharing requirements that lack a direct connection, such as siblings, grandchildren, etc. using a state management solution like RxJS can be highly beneficial.

RxJS provides observables and subjects that facilitate reactive programming and enable efficient data sharing between components. Here, again we use services but with RxJS approach. You can also use a regular RxJS Subject for sharing data via the service, but here’s why I prefer BehaviorSubject.

  • It will always return the current value on subscription – there is no need to call “onNext”.
  • It has a “getValue()” function to extract the last value as raw data.
  • It ensures that the component always receives the most recent data.

Shared Service File:
Rxjs Service

In the service, we create a private BehaviorSubject that will hold the current value of the message. We define a currentMessage variable to handle this data stream as observable that will be used by the components. Lastly, we create a function that calls next on the BehaviorSubject to change its value.

Parent Component
Rxjs Parent

The parent, child, and sibling components all receive the same treatment. We inject the DataService in the constructor, then subscribe to the currentMessage observable and set its value equal to the message variable.

Child Component / Sibling Component:
Rxjs Child

Now if we create a function in any one of these components that changes the value of the message. When this function is executed the new data automatically broadcast to all other components.

5. Sharing data using LocalStorage or SessionStorage

If you need to preserve data across sessions or between various parts of your application, you can store data in the browser’s “localStorage” or “sessionStorage”. However, note that these methods are limited to string-based data.

Local storage is client-side storage for web applications. It stays there as long as it’s not cleared unlike session storage, which lasts for the current browser tab session. Local storage provides up to 5MB of storage, allocated separately for each domain. For example, local storage for the website www.facebook.com will be different from www.twitter.com.

Let’s create a service file named “LocalService” to store data in local storage.
Localstorage Service

To use the LocalService in component file, you need to inject it by importing it into your required component file by creating an instance in the constructor method.
App component:
Localstorage App

After the app component gets loaded it will set value of “id” in local storage via “LocalService” file “saveData()” method, and we can get the same key value by clicking on “getIdFromLocal()” method by calling “getData()” method from “LocalService” file.

The local storage API provides a couple of methods to store, retrieve, remove, and clear the storage.

For Example:

  1. localStorage.setItem(‘token’,’xhja787′)
  2. localStorage.getItem(‘token’)
  3. localStorage.removeItem(‘token’)
  4. localStorage.clear()

Note: localStorage only stores string values. To store objects or arrays, you need to use JSON.stringify to convert them into a string first.

Thus, we can use Local Storage or Session Storage in Angular to share data between components.

Conclusion

In this article, we have explored different methods for sharing data between components in Angular. From simple parent-child communication using input and output properties to advanced solutions like state management with RxJS, you now have a range of options to choose from based on your application’s complexity.

Remember to select the method that best fits your use case and maintain consistent data-sharing practices throughout your application. By adopting appropriate data-sharing techniques, you can ensure efficient component communication and build robust Angular applications.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Aditya Mohite

Aditya Mohite is a Technical Consultant and working as a front-end developer with over four years of experience. He has good knowledge of JavaScript and its' frameworks like React and Angular. Aditya is passionate about creating user-friendly and responsive web applications and likes to seek knowledge and explore the latest front-end technologies.

More from this Author

Follow Us