首页 > 解决方案 > 在类中动态添加方法

问题描述

我正在尝试为将放入会话存储中的项目添加设置器和获取器。我正在服务中编写这些方法。但是当我尝试在我的组件中调用这些函数时出现编译错误。

这是服务:

@Injectable()
export class UtilitiesService {
    public keySet = [
        "CalendarDates", 
        "LastPublishedSchedule", 
        "ManageStores",
        "SelectedStore"
    ];

    constructor() {
        this.addGetSetClearFunctions();
    }

    addGetFunction(key: string) {
        UtilitiesService["get" + key] = function() {
            return JSON.parse(sessionStorage.getItem(key));
        }
    }

    addSetFunction(key: string) {
        UtilitiesService["set" + key] = function(value) {
            sessionStorage.setItem(key, JSON.stringify(value));
        }
    }

    addClearFunction(key: string) {
        UtilitiesService["clear" + key] = function() {
            sessionStorage.removeItem(key);
        }
    }

    clearAll() {
        sessionStorage.clear();
    }

    addGetSetClearFunctions() {
        for(let i = 0; i < this.keySet.length; i++) {
            this.addGetFunction(this.keySet[i]);
            this.addSetFunction(this.keySet[i]);
            this.addClearFunction(this.keySet[i]);
        }
    }
}

我试图在组件内的 set 方法内调用:

this.utilService.setLastPublishedSchedule(JSON.stringify(response));

注意:utilService被正确注入,它的其他辅助功能(我这里没有放)执行成功。

编辑#1:这是我得到的错误:

src/app/dashboard/components/schedule/schedule.component.ts(344,22) 中的错误:错误 TS2339:“UtilitiesService”类型上不存在属性“setLastPublishedSchedule”。

编辑#2:我尝试通过以下方式调用该方法:

this.utilService['setLastPublishedSchedule'](argument here)

我收到了这个运行时错误:

错误类型错误:_this.utilService.setLastPublishedSchedule 不是函数

标签: angulartypescriptangular5

解决方案


该错误表明该方法不存在。有一些方法可以解决这个问题(比如强制转换为any),但它们会破坏类型安全。更好的解决方案是添加一个将密钥作为参数的方法,并以这种方式调用它。

setValue(key: "CalendarDates"|"LastPublishedSchedule"|"ManageStores"|"SelectedStore", value: string) {
   sessionStorage.setItem(key, value);
}
this.utilService.setValue("LastPublishedSchedule", JSON.stringify(response));

您可以对其他方法重复此模式,例如检索值或清除值。

此外,您不必将键限制为值列表,但因为我注意到您确实对使用的键有限制,所以我将其添加到 key 参数参数中。


推荐阅读