【发布时间】:2021-06-23 08:25:13
【问题描述】:
我正在尝试创建一个覆盖 (Angular CDK) 服务,该服务具有接收不同类型组件的通用方法。这只是为了避免为每个将显示在叠加层中的组件提供单独的服务,特别是因为它们几乎都相同,除了注入器。
最简单的形式应该是这样的:
createOverlay<T extends Component>() : void
{
const portal = new ComponentPortal(T);
}
但我得到一个“'T' 仅指一种类型,但在这里被用作一个值。”错误,即使 ComponentPortal 构造函数确实需要一个类型。
我想我可以将调用 createOverlay() 方法的组件作为参数传递,但是,正如您将看到的,我显然不知道如何获取类型所述参数:
createOverlay(component: Component) : void
{
const overlayRef = this.overlay.create();
const portal = new ComponentPortal(typeof component);
}
感谢您的指正和建议。
有什么想法吗?
ComponentPortal 构造函数:
constructor(component: ComponentType<T>, viewContainerRef?: ViewContainerRef | null, injector?: Injector | null, componentFactoryResolver?: ComponentFactoryResolver | null);
ComponentType 实际上是一个接口:
export interface ComponentType<T> {
new (...args: any[]): T;
}
【问题讨论】:
-
能否提供
ComponentPortal构造函数的签名? -
我将其添加到原始帖子中作为编辑。
-
太棒了。请注意,没有将类型作为值传递这样的事情。类型和接口是值可以采用的形状。您可以对它们进行一些操作,例如类型联合、扩展等,但不能将它们作为参数传递给方法或函数。无论如何:请不要认为构造函数采用的组件是
ComponentType<T>类型,它是一个类。您必须创建一个扩展ComponentType的类,实例化它并将实例作为参数传递给ComponentPortal构造函数。 -
ComponentType
是一个接口,使事情变得更复杂。它里面唯一的东西是一个方法,我想,它将实例化你分配给它的任何类型的 T 类。我将其添加到原始帖子中。
标签: angular typescript generics overlay typeof