简体   繁体   English

如何在组件中使用角度6类装饰器?

[英]How to use angular 6 class decorator in a component?

I create a component in angular 6 with sample on how to implement decorators. 我用关于如何实现装饰器的示例在angular 6中创建了一个组件。 So, I create a custom decorator called @Course and set a value there, named Angular 6. Now, how to get that value in my component's constructor? 因此,我创建了一个名为@Course的自定义装饰器,并在其中设置了一个名为Angular 6的值。现在,如何在组件的构造函数中获取该值?

I want to log the "Angular 6" value to my constructor. 我想将“ Angular 6”值记录到我的构造函数中。 How's that possible? 那怎么可能

Here is my code. 这是我的代码。 Work's fine. 工作正常。 I've got the value. 我有价值。 But got an error in command line 但是在命令行中出现错误

ERROR in src/app/components/decorators/decorators.component.ts(19,22): error TS2339: Property 'course' does not exist on type 'DecoratorsComponent'.

import { Component, OnInit } from '@angular/core';

function Course(target) {
  Object.defineProperty(target.prototype, 'course', {
    value: () => "Angular 6"
  })
}

@Course
@Component({
  selector: 'app-decorators',
  templateUrl: './decorators.component.html',
  styleUrls: ['./decorators.component.scss']
})
export class DecoratorsComponent implements OnInit {

  constructor() {
    console.log(this.course());
  }

  ngOnInit() {
  }
}

target.prototype.course =()=>'Angular 6';

You just need to tell TypeScript compilier about dynamically added property. 您只需要告诉TypeScript编译器有关动态添加的属性。 The simplest way : 最简单的方法

@Course
// ...
export class DecoratorsComponent implements OnInit {
    // ... 
    [key: string]: any;
}

Alternatively, you read the dynamic property as "array item": 或者,将动态属性读取为“数组项”:

constructor() {

    const courseProp = this['course'];

    if (courseProp) {
        console.log(courseProp());
    }
}

NOTE: it is good practice to check existence of the property, because decorator may be removed. 注意:最好检查属性是否存在,因为装饰器可能会被移除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM