【问题标题】:Angular2 2.0.0 How to add simple functions to @NgModuleAngular2 2.0.0 如何向@NgModule 添加简单的功能
【发布时间】:2017-02-03 05:10:01
【问题描述】:

我想创建一个“实用模块”:tnt.module.ts:

import {NgModule} from '@angular/core';
import {toUpperCase} from "./tnt.utils";

@NgModule({
  declarations: [
    toUpperCase
  ],
  exports: [
    toUpperCase
  ]
})
export default class TntModule {}

这里是一个 util 函数示例:tnt.utils.ts

export const toUpperCase= function (str:String) {
  return str.toUpperCase()
}

我收到一个错误:

ERROR in [default] /data/2016/le-tube/src/app/shared/tnt/tnt.module.ts:5:10 
Argument of type '{ imports: undefined[]; declarations: ((str: String) => string)[]; exports: ((str: String) => str...' is not assignable to parameter of type 'NgModule'.
  Types of property 'declarations' are incompatible.
    Type '((str: String) => string)[]' is not assignable to type '(any[] | Type<any>)[]'.
      Type '(str: String) => string' is not assignable to type 'any[] | Type<any>'.
        Type '(str: String) => string' is not assignable to type 'Type<any>'.
          Type '(str: String) => string' provides no match for the signature 'new (...args: any[]): any'

我错过了什么?为什么我不能创建具有简单功能的模块?我想我只是错过了一个简单的细节,但我无法弄清楚......

【问题讨论】:

  • 我无法从提供的信息中回答。但是,我可以建议您使用 angular cli:github.com/angular/angular-cli 和 toUppercase 在我看来是一个“管道”候选人。对于功能,您应该使用服务。
  • 我正在使用 angular-cli,我明白了,谢谢,我将建立一个服务。

标签: angular ng-modules


【解决方案1】:

你不能从 NgModule 导出函数,

出口:数组|任何[]>

指定一个列表 可以在任何模板中使用的指令/管道/模块 作为导入此角度的角度模块的一部分的组件 模块。

阅读更多关于它的信息here

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    您不能从模块中导出函数。

    你有两个选择:

    1) 创建一个utililty.ts 文件并在其中创建要导出的函数。

    export function utlityFunction1(param1, param2) { return param1+param2; )
    

    您可以像任何其他对象一样在代码文件中导入此函数。

    import { utilityFunction } from './utility.ts'
    

    2) 创建一个UtilityService 并将其注入到您的组件中。

    更多信息在这里https://angular.io/docs/ts/latest/guide/dependency-injection.html

    【讨论】:

      猜你喜欢
      • 2012-01-13
      • 1970-01-01
      • 1970-01-01
      • 2017-04-17
      • 2019-03-12
      • 2018-04-30
      • 2015-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多