【问题标题】:How to export simple TypeScript class in Angular 4 module?如何在 Angular 4 模块中导出简单的 TypeScript 类?
【发布时间】:2019-01-04 00:30:24
【问题描述】:

我有一个简单的 TypeScript 类,我想将它与一个模块一起打包,并最终使用 ng-packagr 将该模块导出为一个库。

例如我的班级定义是 -

export class Params {
    language: string ;
    country: string ;
    variant:  string ;
    dateFormat:  string ;
    briefDateTimeFormat:  string ;
    decimalFormat:  string ;
}

例如我的模块定义是 -

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Params } from '../params/params';
import { LoginService } from '../sso/login.service';

@NgModule({
  imports: [CommonModule],
  exports: [Params],
  providers: [LoginService]
  declarations: [Params, LoginService]
})
export class FoundationModule { }

但是当我尝试在ng-packagrpublic-api.ts 中导出FoundationModule 时,出现以下错误 -

BUILD ERROR
: Unexpected value 'Params in .../params/params.ts' declared by the module 'FoundationModule' in '.../foundation.module.ts'. Please add a @Pipe/@Directive/@Component annotation.

如何在 Angular 模块中打包单个类?

【问题讨论】:

  • 不确定是否必须创建构造函数来完成类,另一种选择是将其保留为接口。
  • 我认为您需要添加 export * from '../params/param'。我使用它来导出我的类以进行汇总,以获得平面 es 模块
  • 您混淆了 Angular 模块和 es 模块。此外,Params 不应该是一个类。使用interface

标签: angular typescript angular-module ng-packagr


【解决方案1】:

两个选项。

export class Params {
language: string;
country: string;
variant: string;
dateFormat: string;
briefDateTimeFormat: string;
decimalFormat: string;
constructor(obj: any) {
    this.language = obj && obj.language || null;
    this.country = obj && obj.country || null;
    this.variant = obj && obj.variant || null;
    this.dateFormat = obj && obj.dateFormat || null;
    this.briefDateTimeFormat = obj && obj.briefDateTimeFormat || null;
    this.decimalFormat = obj && obj.decimalFormat || null;
}

}

export interface Params {
    language: string;
    country: string;
    variant: string;
    dateFormat: string;
    briefDateTimeFormat: string;
    decimalFormat: string;
}

正如第一个答案所说,类或接口不在模块上。

Stackoverflow reference

Angular reference

【讨论】:

    【解决方案2】:

    问题出在您的模块定义中。您应该直接将Params 导入到需要该类的每个组件/服务中。

    public-api.ts

    import { Params } from '../params/params';
    
    ...
    newVariable: Params = {
      language: 'my language',
      ...
    }
    

    【讨论】:

    • 如果您将其设为 interfacetype 声明,则很好。这是对类的错误使用
    • @AluanHaddad 如果他没有构造函数,他应该将其设为接口!很好的收获。
    • 也许会修改您的答案,但我认为他也将语言和框架概念混为一谈。可能很好解释import/export@ngModuleimports/exports 之间的区别。
    猜你喜欢
    • 1970-01-01
    • 2020-06-27
    • 2017-02-22
    • 1970-01-01
    • 2019-06-06
    • 2022-11-26
    • 2021-07-04
    • 2019-05-09
    相关资源
    最近更新 更多