简体   繁体   中英

Using Angular's routes collection for populating a navigation area

When developing apps in Angular 2 I find myself having redundant code in my app when it comes to routes. Once I have my routes exported from a file for RouterModule use, I would imagine it to become a single source of truth - re-used for populating navigation areas in the app.

The problem is, that the Route interface item does not allow any kind of 'label' attribute. If it did, I could iterate over the array, pick up a specified level (root or children or any route) and if the path was not '' or ** I would return the item and use its label .

Now, as wishful as it sounds, I just wanted to describe the problem. Has anyone come up to a sneaky solution for that purpose?

For a moment I thought of cloning the routes collection and applying my own labels on top of each item, but it would again produce some unnecessary code on another end

The routes in an Angular application are just an array of objects. In other words, they're a JavaScript variable. How you obtain this variable is up to you.

You could have an allRoutes variable acting as the single source of truth:

// Note that I haven't used the `Routes` type.
// You could define your own interface for this.
const allRoutes: any[] = [
  { path: 'home', component: HomeComponent, label: 'Home' },
  { path: 'contact', component: ContactComponent, label: 'Contact' },
  // ...
};

Then, use that to generate router-compatible routes:

// Iterate over `allRoutes` to produce the following.
// The `label` property is gone.
const routerFriendlyRoutes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'contact', component: ContactComponent },
  // ...
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM