在 Angular 路由中使用泛型

Use generics in Angular route

我想知道是否可以在 Angular Route 中以任何可能的方式使用 (Typescript) 泛型。

最好的方法是,如果我可以对组件本身使用泛型:

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

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

这显然是一个错误,但它很好地说明了我想要完成的事情。

另一种方法是将泛型与 Resolver:

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

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

使用了这个方法,但对我来说它在 UserResolver<UserB> 处给出了一个错误: "Value of type 'typeof UserResolver' is not callable. Did you mean to包括 'new'?"

不知道我怎么会错过这个,但是 angular 路线上 data 属性 的值可以是 any 类型。这意味着您可以这样做:

// 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'];
  }

}

不知何故,我总是假设数据 属性 的值只能是一个字符串,但文档明确指出 any.