1

I have a Angular application, which has multiple components that access the same Service.

I am trying to understand if there is any benefit to switching away from using route parameters to using variables in the common service?

1
  • With query params the values will be persisted in the URL, so when the page is refreshed, or the link is saved somewhere, those parameters will apply again when the link is used. With a service, those values are lost after closing the page. Commented Nov 18, 2024 at 11:11

1 Answer 1

1

I am trying to understand if there is any benefit to switching away from using route parameters to using variables in the common service?

Route params and query params holding state:

  • If you want your application to hold the state of the page even during reload, store it in the URL params and query params.

  • If you want to pass important information like the ID of a product use params (/:id), if it's not mandatory information use query params (?test=1)

Storing state in services:

  • If you want your application to not hold the state of the page even during reload, but just want to communicate the data.

  • Using this method declutters the URL for sharing information.

  • easy communication between any level of components ( distantly related to each other, not parent to child or vice versa )

Disadvantages:

  • If your service is providedIn: 'root' then the service is never destroyed until you reset it manually. The properties state is maintained throughout the life of the application (cleared only on refresh)

  • You have to ensure the state is reset and no data collisions happen with other component linkages.

Key Takeaways:

  • Prefer routing based state storage when you want to store state even when page is refreshed.

  • It is ok to use services based storage, but you need to take into account the lifecycle of the properties state. It should no collide with other component having previous state.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.