Search code examples
javascriptangulartypescriptrefactoringangular-routing

Angular Router pass data to component


Is it a good practice to pass data with the angular router to a component or should i use an service instead?

At the moment the component gets the data like this:

this.account = activatedRoute.snapshot.data.account

Solution

  • There are several ways to pass data to an angular component.

    For objects like user account, I would use a provider (to have it ready on component init), a service (for sharing around app) or a guard (e.g. if you want to navigate out when not logged in).

    When I want to reuse the same component in different routes and give it some hints about is behavior, I would use router data.

    Another use case I met is to define a global app state using the activated route(s). Each route may define its data, a service listen for router events and stores the merged state. It helps me with large apps to have a route-based configuration for title, metas, toolbar and menus visibility, etc...