【问题标题】:Cannot add a new method to an Angular TypeScript class (FormGroup)无法向 Angular TypeScript 类 (FormGroup) 添加新方法
【发布时间】:2017-12-09 04:17:06
【问题描述】:

我正在尝试向 Angular 的 FormGroup 类添加一个额外的方法,该方法将设置组的状态 + 从服务器设置错误状态。

我的 Angular4 应用程序的 form-helper.ts 文件中有以下代码。

import { FormGroup } from '@angular/forms';

export interface FormGroup {
  setValueAndErrors(state: any, memberErrors: any);
}

FormGroup.prototype.setValueAndErrors = (state: any, memberErrors: any) => {
  this.setValue(state);
  // do some stuff with the memberErrors parameter
}

但编译器在FormGroup.prototype.setValueAndErrors 行抛出错误。

C:/dev/AppName/AppName-Client/src/app/shared/utils/form-helper.ts (3,21) 中的错误:“FormGroup”类型上不存在属性“setValueAndErrors”。

【问题讨论】:

  • 除了你提到的错误之外,this 不会是你所期望的箭头函数。
  • 我可以跨过那座桥 :) 现在我只想知道为什么它没有编译

标签: angular typescript


【解决方案1】:

以下为我编译:

declare module "@angular/forms/src/model" {
  interface FormGroup {
    setValueAndErrors(this: FormGroup, state: any, memberErrors: any): void;
  }
}

FormGroup.prototype.setValueAndErrors = function(this: FormGroup, state: any, memberErrors: any): void {
  this.setValue(state);
}

该键似乎使用了引用包含FormGroup 的实际模块/文件的模块名称。

此外,您还需要解决您对this 的使用问题。

【讨论】:

  • 你对我来说就像一个英雄:)
  • 不用担心。回答这个问题帮助我解决了困扰我一整天的问题。
  • 将其作为问题+答案发布在这里,以节省其他人的时间:)
  • 你太棒了!
猜你喜欢
  • 1970-01-01
  • 2019-07-15
  • 2017-11-14
  • 2018-03-21
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 2020-08-03
相关资源
最近更新 更多