加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular4组件继承与抽象类

发布时间:2020-12-17 07:18:00 所属栏目:安全 来源:网络整理
导读:我想为我的组件定义一个基类来共享一些功能.所以我开始: export abstract class BaseComponent { protected getName(): string;}@Component(...)export class MyComponent extends BaseComponent { protected getName(): string { return "MyComponent"; }}
我想为我的组件定义一个基类来共享一些功能.所以我开始:
export abstract class BaseComponent {
    protected getName(): string;
}

@Component(...)
export class MyComponent extends BaseComponent {
    protected getName(): string {
        return "MyComponent";
    }
}

但是在我需要为BaseComponent添加一些注释之后就像@HostListener(‘window:keydown’,[‘$event’]).所以我必须将@Component添加到BaseComponent以启用角度注释.一切都很好……直到我尝试在生产模式下编译

ng build –prod

Cannot determine the module for class BaseComponent

所以我已经将BaseComponent添加到@NgModule,但我有:

No template specified for component BaseComponent

所以我补充说

@Component({template: ''})

但我有 :

Argument of type ‘typeof BaseComponent’ is not assignable to parameter of type ‘Type’. Cannot assign an abstract constructor type to a non-abstract constructor type.

所以我删除了“abstract”关键字,以便在生产模式下编译我的项目.

你有解决方案吗?我不喜欢糟糕的概念!

无需将@Component()注释添加到抽象类或将它们注册到任何模块.

可能是您的代码中存在一些不符合Angular期望的错误.

我使用Angular CLI 1.2.7创建了一个演示应用程序,其中包含ng new< name>命令并扩展AppComponent类,如下所示.

base.component.ts

import { HostListener } from '@angular/core';

export abstract class BaseComponent {
    @HostListener('click')
    onClick() {
        alert('Click');
    }
}

app.component.ts

import { Component } from '@angular/core';
import { BaseComponent } from './base.component';

@Component({
    selector: 'app-root',templateUrl: './app.component.html',styleUrls: [ './app.component.css' ]
})
export class AppComponent extends BaseComponent {
    title = 'app';
}

app.module类没有以任何方式更改.

位于基本组件中的单击处理程序没有任何问题.使用ng build –prod的AOT编译也没有给出任何错误.

这个演示使用了角度v5.1.1

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读