Search code examples
angularangular-servicesangular-routerurlsearchparamsangular-router-params

Using Common Service Variables or Route Parameters


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?


Solution

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