在 Angular 路由中使用泛型

问题描述

我想知道是否可以在 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> { ... }

这显然给出了一个错误,但它很好地说明了我想要完成的任务。

另一种方法是使用带有 @L_404_1@ 的泛型:

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

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

This answer 使用了这种方法,但对我来说,它在 UserResolver<UserB> 处出现错误“类型 'typeof UserResolver' 的值不可调用。您的意思是包含 'new' 吗? “

解决方法

不知道我怎么会错过这个,但是角度路由上的 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