代码之家  ›  专栏  ›  技术社区  ›  jcubic

如何在代码笔上向Angular7应用程序添加指令

  •  1
  • jcubic  · 技术社区  · 7 年前

    我正在学习Angular,我正在学习Udemy的教程并检查文档。我是我创造的 Angular app on Codepen

    现在我正试图定义指令,但出现了错误:

    未捕获错误:无法解析指针方向的所有参数: (?).

    我的代码如下:

    @Directive({
        selector: '[pointer]'
    })
    class PointerDirective implements OnInit {
        constructor(private element: ElementRef) { }
        ngOnInit() { }   
    }
    
    @NgModule({
      imports: [
          BrowserModule,
          CommonModule
      ],
      declarations: [ PointerDirective, AppComponent ],
      providers: [],
      bootstrap: [ AppComponent ]
    })
    class AppModule {}
    

    我还尝试了不同的名称(应用程序指针),但得到了相同的错误。

    这支笔是根据 this one 但在这里它也不起作用。

    在搜索这个错误时,我得到了信息,这可能是循环依赖关系,但这里我只是有一个简单的指令。发生了什么?

    编辑 :

    根据@trichtriche的说法,代码只在codepen上不起作用,我是否遗漏了一些文件?如何创建基本的角度项目而不使用构建过程,只使用脚本标记?我怎样才能使角度应用程序在代码笔中工作?

    编辑2 :

    所以我想出来了:

    @Directive({
        selector: '[pointer]'
    })
    class PointerDirective implements OnInit {
        constructor(@Inject(ElementRef) private element: ElementRef) {
        }
        ngOnInit() { }   
    }
    

    如果你知道为什么 @Inject 在代码笔上是必需的,而不是在正常项目中添加答案。

    1 回复  |  直到 7 年前
        1
  •  1
  •   yurzui    7 年前

    在代码笔示例中,您使用typescript作为预处理器,以便所有代码都由typescript编译。

    Angular有内置的DI系统,很大程度上依赖于我们在TS代码的构造函数中提供的类型。

    constructor(private element: ElementRef) { }
                                 ^^^^^^^^^^^
                      we have to keep this type after ts compilation
    

    默认情况下,typescript在编译后不保留该信息,但我们可以设置一个名为 emitDecoratorMetadata 为了保持这种类型:

    __metadata("design:paramtypes", [ElementRef])
    

    但是codepen似乎没有这样的选择来改变这一点 tsconfig.json 因此,您必须自己将该类型提供给编译后的版本。

    以下是几个选项:

    1)专用 @Inject 装饰者:

    constructor(@Inject(ElementRef) private element: ElementRef) {}
    

    2)静态 parameters 类类型上的属性:

    class PointerDirective implements OnInit {
      constructor(private element: ElementRef) {}
    
      static parameters = [ ElementRef ]
    

    3)静态 ctorParameters 方法:

    class PointerDirective implements OnInit {
      constructor(private element: ElementRef) {}
    
      static ctorParameters = () => [{ type: ElementRef }]
    

    Forked Codepen

    推荐文章