简体   繁体   中英

How to reuse a component code (Angular2 + TS)

Creating a small Angular 2 app (A calculator for a nice game called AbyssRium), I'm trying to reuse the code of a simple component that shows a list of elements. I want those components to show only a subset of elements (filtered by group).

I'm not sure if it's possible to do it using the RouteConfig (passing a parameter), but it would be a good option. I tried to understand 'Routes' the documentation ( here and here ) but I couldn't see any clear reference (now playing with Resolve , but no results yet). I'm looking for something like this:

@RouteConfig([
  {path: '/corals', name: 'Corals', component: ItemsList, data:{group:'coral'}, useAsDefault: true},
  {path: '/fishes', name: 'Fishes', component: ItemsList, data:{group:'fish'}},
])

I also tried to inherit the module (ItemsList -> ItemsCoralList & ItemsFishList), and initialize the class (this.group = "coral") in the constructor, but tons of compilation errors appear:

Cannot resolve 'xxx'. Make sure they all have valid type or annotations.

Any idea how to do it without copying all the code twice?

Here the code at Plunker

You can use:

{path: '/:group', component: ItemsList}

And access it via router

constructor(route: ActivatedRoute) {
  this.route.params.subscribe(params => params.group)
}

Note: this is Router 3.x syntax, it's probably not gonna work out of the box - you should upgrade to final...

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