Home > Net >  Angular Router pass data to component
Angular Router pass data to component

Time:10-02

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

CodePudding user response:

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

CodePudding user response:

If you want to pass data through a route, here is a simple example.

Make your route to look like this:

{ path: 'todo', component: TodoComponent, data: { id:'1', name:"Todo Title"} }

Then in your Component you can do something like this:

ngOnInit() {
      this.activatedroute.data.subscribe(data => {
          this.todo = data;
      })
}

Was this helpful?

  • Related