Home > other >  Extracting Navigation Logic From Angular Components
Extracting Navigation Logic From Angular Components

Time:09-23

I have a number of Angular components all with routing setup so that there is a specific url for each one. The requirement is that I need to navigate from one to the next in a series based on what data the user enters along the way. Some of these components will be used multiple times at different stages along the way.

I could add the logic in each component to work out which is the next component to go to, but I feel like this logic should be extracted out into a separate class somewhere which can view all the data collected so far, but I can't work out the right way to do this.

Any suggestions? Are there examples of this type of pattern anywhere?

CodePudding user response:

That's what service are for.

Create a service that manage all of the data required for routing, and routes according to this data.

This way, the service becomes your single source of truth when it comes to routing, which is a good practice. For instance, if you have to change a route later on, you won't have to browse every file to update it, just the service.

EDIT : an idea of the service

export class RoutingService {

  private data: any;

  constructor(private router: Router) {}

  startDataConstruction(params: any) {
    this.data = params;
  }

  updateData(params: any) {
    if (!this.data) 
      throw new Error('please construct your data first');
    Object.assign(this.data, parems);
  } 

  dataRoute() {
    // Do your routing logic here then
    delete this.data;
  }

}
  • Related