1

I have a projects overview as entry page.

When I click the open project button the projectId is passed to the Milesstones view. When I am in the milestones view I want to activate the Tasks view with the projectId.

This scenario would easily be possible with a milestones/tasks being child routes, but they are NOT! All 3 views belong to top level routes.

AFAIK using child routes means the components must also be children in the ui hierarchy so I can not have 3 parallel/sidebyside views.

How else can I achieve what I want?

enter image description here

Pascal
  • 12,265
  • 25
  • 103
  • 195

1 Answers1

0

Create a service and inject it into each of your three components.

Inside this service create methods setProject(projectID) and getProject(). When the user clicks on the button open, invoke this method on the service passing the selected project.

Inside the method setProject() store the selected projectID in a class variable and using a class var of type EventEmitter emit the event that carries the selected projectID as a payload.

In the constructors of two other components immediately invoke getProject() on the service and subscribe to that EventEmitter.

This way as soon as the user clicks on the Milestones or Tasks links, they'll get the project ID. Moreover, if the user selects a different project while one of the other routes is active, the new value will be available to that underlying component via subscription.

Yakov Fain
  • 11,972
  • 5
  • 33
  • 38
  • Funny the same idea I had this morning about a singleton service. But I did not understand your last paragraph. How can the user select another project in the UI while he is still on another route? – Pascal Dec 29 '16 at 11:30
  • This may not be your case, but it's possible to keep a list of projects in the landing page, while milestones and tasks are displayed in the router outlet. In this case you may have both projects and milestones(or tasks) displayed on the UI at the same time. – Yakov Fain Dec 29 '16 at 12:36
  • Is there a reason why constructor and not ngOnInit for the: this.projectsStore.observer.asObservable().subscribe(p => { this.projectsId = p; alert(p); }); – Pascal Dec 30 '16 at 22:27
  • Hmm... that can not work. When I set the projectId via open button the tasks component is not yet initialized! Thus it can not listen for the emit of the projectId via open button click. How is that solved Yakov? Hm ok that should not matter as the projectStore being a singleton can be retrieved to get the projectId! Still fumbling around! – Pascal Dec 30 '16 at 22:38
  • You don't care if the tasks is initialized. At some point it's going to be created, so in the task's constructor get the projectID from the service (using a simple getter) and then optionally subscribe. – Yakov Fain Dec 31 '16 at 00:02
  • Ok it works nice above all when the unsubscribe is done correctly ;-) – Pascal Dec 31 '16 at 12:41