将属性设置为在typescript类中触发方法

时间:2018-06-18 15:23:51

标签: angular typescript class

我目前正在尝试在我的类中设置一个属性,以便在调用它时,它将在同一个类中触发一个方法来执行。我似乎收到了很多与... is not a function相关的错误。

所以我试图以不同的方式实现这一点。

所以我已经设置了很多属性和构造函数的类,我试图设置一个属性html,它将触发方法getHTML()被触发:

export class DocumentTemplateHistoryDto {
Id: string;
Agent: AgentDto;
AgentId: string;
CreatedDate: Date;
Draft: boolean;
EndDate: Date;
HeaderAndFooter: HeaderAndFooterDto;
HeaderAndFooterId: string;
Live: boolean;
StartDate: Date;
DocumentTemplate: DocumentTemplateDto;
DocumentTemplateId: string;
VersionNumber: number;
Pages: PageDto[];
_MergedHTML: string;
html: () => void;

constructor(_Agent: AgentDto, _AgentId: string, _CreatedDate: Date, _Draft: boolean, _EndDate: Date, _HeaderAndFooter: HeaderAndFooterDto, _HeaderAndFooterId: string,
    _Live: boolean, _StartDate: Date, _DocumentTemplate: DocumentTemplateDto, _DocumentTemplateId: string, _VersionNumber: number, _Pages: PageDto[], _Id?: string) {

    this.Agent = _Agent;
    this.AgentId = _AgentId;
    this.CreatedDate = _CreatedDate;
    this.Draft = _Draft;
    this.EndDate = _EndDate;
    this.HeaderAndFooter = _HeaderAndFooter;
    this.HeaderAndFooterId = _HeaderAndFooterId;
    this.Live = _Live;
    this.StartDate = _StartDate;
    this.DocumentTemplate = _DocumentTemplate;
    this.DocumentTemplateId = _DocumentTemplateId;
    this.VersionNumber = _VersionNumber;
    this.Pages = _Pages;
    this.Id = _Id;


}

getHTML() {
    this.Pages.forEach((item) => {
        this._MergedHTML = this._MergedHTML + item.HTML;
    });
}
}

我似乎无法获得此功能的正确语法。有人可以帮帮我吗。

1 个答案:

答案 0 :(得分:0)

有几种方法可以做到这一点,但对我来说立即想到的是吸气剂或代理。

Getters和setter可能是实现您想要的最简单方法,如下所示:

df1[paste0(colnames(df1), "_index")] <- lapply(df1, function(x) df2$Index[match(x, df2$Country)])

然后叫它:

export class DocumentTemplateHistoryDto {

    ...

    public get html(){
        this.Pages.forEach((item) => {
            this._MergedHTML = this._MergedHTML + item.HTML;
        });
    }
}

警告您可以设置代理:

new DocumentTemplateHistoryDto().html;

然后叫它:

export class DocumentTemplateHistoryDto {

...

public htmlProxy = new Proxy ({
    get: (obj, prop) => {
        if(prop === 'html')
            this.Pages.forEach((item) => {
                this._MergedHTML = this._MergedHTML + item.HTML;
            });
      return true;
    }
});