Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

angular2 routing - Use generics in Angular route

I want to know if it's possible to use (Typescript) generics in a Angular Route, in any way possible.

Best way would be if I could use generics with the component itself:

// the route:
{
  path: 'user-a',
  component: UserComponent<UserA> // other routes will use UserB and UserC
}

// the component:
@Component({...})
export class UserComponent<T> { ... }

This obviously gives an error, but it gives a good idea of what I want to accomplish.

Another method would be to use generics with the Resolver:

// the route:
{
    path: '/user-b',
    component: UserComponent, 
    resolve: { user: UserResolver<UserB> }
}

// the resolver:
export class UserResolver<T> implements Resolve<boolean> {}

This answer used this method, but for me it gives an error at UserResolver<UserB>: "Value of type 'typeof UserResolver' is not callable. Did you mean to include 'new'?"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Not sure how I could of missed this, but the value of a data property on a angular Route can be of any type. Which means you can do this:

// the route in app-routing.module.ts
{
  path: 'user-a',
  component: UserComponent,
  data: {
    componentType: UserA
  }
}

// UserComponent:
@Component({...})
export class UserComponent implements OnInit {

  constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {
    const componentType: any = this.route.snapshot.data['componentType'];
  }

}

Somehow I always assumed the value of a data property could only be a string, but the docs clear state any.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...