【问题标题】:Angular- service providing components (TS error)Angular-服务提供组件(TS错误)
【发布时间】:2018-12-11 03:36:09
【问题描述】:

我第一次尝试动态注入组件。到目前为止,我现在非常成功,但是我有一个来自 Typescript 的错误,这让我很烦恼(不喜欢我的代码中有错误)

这是应用程序的链接:https://stackblitz.com/edit/angular-vrtr51?embed=1&file=src/app/app.component.ts

我的目标是让服务能够为我提供我需要的任何组件,从任何地方注入它(对于基于小部件的网站)。

但我在控制台中有此错误消息: 错误 TS2339:类型“{}”上不存在属性“数据”。

你可以在 app.component.ts 的第 35 行看到它

代码运行良好,但我想了解为什么会出现此错误消息。

谢谢!

【问题讨论】:

    标签: angular typescript


    【解决方案1】:
    const factory = this.resolver.resolveComponentFactory(this.compProvider.get('header'));
    

    如果您查看factory 的类型,它是ComponentFactory<{}>。这是因为您正在使用返回任何类型的服务获取组件类型。

    export class ComponentProviderService {
      public get(id): any {
        console.log(this.componentMap[id]);
        return this.componentMap[id];
      }
    }
    

    当您在第 30 行执行以下操作时,您正在使用 factory 的类型创建组件,该类型隐式为 ComponentFactory<{}>,因为该服务返回 any

    const comRef = this.headerContainer.createComponent(factory);
    

    因此,comRef 最终是 ComponentRef<{}> 类型,它具有属性 instance,但 instance 的类型是 {},这是给您错误的部分:Property 'data' does not exist on type '{}'.

    如果将第 29 行替换为

    const factory = this.resolver.resolveComponentFactory(HeaderComponent);
    

    它现在可以正常工作,没有错误,因为factory 的类型现在明确为ComponentFactory<HeaderComponent>,这反过来意味着comRef 的类型是ComponentRef<HeaderComponent>,这又意味着属性@987654340 @ 现在是 HeaderComponent 类型。

    【讨论】:

    • 好的,谢谢,我明白了!我对您的解决方案的问题是我必须导入我需要在应用程序组件中注入的所有组件,这是我试图避免的。因此,为了让我的服务返回许多不同的组件,我刚刚将 ComponentRef 的实例声明为 any: const comRef: ComponentRef = this.headerContainer.createComponent( factory );由于我无法使用我将返回的组件类型来键入它,我认为 any 是这里唯一可能的类型。
    • @Projeer 我并不是说你应该直接使用HeaderComponent 作为你的解决方案。您的问题只是“我想了解为什么会出现此错误消息。”我只是在解释,如果你改用HeaderComponent,你就不会再看到错误了。但是,是的,将您拥有的factorycomRef 变量分别明确声明为ComponentFactory<any>ComponentRef<any> 也可以解决这个问题。权衡是您丢失了那些强类型属性,但这可能是使用返回 any 的服务来完成您所做的事情的唯一方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    • 2017-02-15
    • 2017-11-11
    • 2020-12-21
    • 1970-01-01
    • 2018-12-14
    相关资源
    最近更新 更多