0

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
2
  • 1
    Uh, I've never seen this method of passing data through the router. Seems like a clumsy hack to me. The router is for routing, and services are for sharing data across components. Commented Oct 1, 2021 at 8:31
  • Okay i have the same feeling ;) Thanks for your response. Commented Oct 1, 2021 at 8:58

2 Answers 2

4

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?

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

2 Comments

Yes thanks, but passing data threw an service is the better practice or am i wrong?
Yes, you are right. There are three ways to pass data from component to component, excluding passing through routes. Input and Output Decorators and Service. In service, you can store some data and pull that data into components that you wish. Now, if you wish to immediately get data from the service once it was emitted, you can use the RxJS feature called Subject. Create a Subject, emit data from Component A, and in Component B make sure to subscribe to that subject to always get the latest data. Just make sure to unsubscribe from the subject, to prevent memory leaks.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.