Angular 在类中动态添加方法
我正在尝试为将放入会话存储中的项添加setter和getter。我正在服务中编写这些方法。但当我试图在我的组件中调用这些函数时,我得到了transfile错误 服务内容如下:Angular 在类中动态添加方法,angular,typescript,angular5,Angular,Typescript,Angular5,我正在尝试为将放入会话存储中的项添加setter和getter。我正在服务中编写这些方法。但当我试图在我的组件中调用这些函数时,我得到了transfile错误 服务内容如下: @Injectable() export class UtilitiesService { public keySet = [ "CalendarDates", "LastPublishedSchedule", "ManageStores", "S
@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]);
}
}
}
注意:utilService被正确注入,它的其他辅助功能(我没有放在这里)正在成功执行
编辑#1:这是我得到的错误:
错误
src/app/dashboard/components/schedule/schedule.component.ts(344,22):
错误TS2339:上不存在属性“setLastPublishedSchedule”
键入“UtilitiesService”
编辑#2:
我尝试通过以下方式调用该方法:
this.utilService['setLastPublishedSchedule'](argument here)
我得到了这个运行时错误:
错误类型错误:\ u this.utilService.setLastPublishedSchedule不是
作用
该错误表示该方法不存在。有很多方法可以解决这个问题(比如对
any
进行强制转换),但它们破坏了类型安全性。一个更好的解决方案是添加一个将键作为参数的方法,并以这种方式调用它
setValue(key: "CalendarDates"|"LastPublishedSchedule"|"ManageStores"|"SelectedStore", value: string) {
sessionStorage.setItem(key, value);
}
您可以对其他方法(如检索值或清除值)重复此模式
另外,您不必将键约束到值列表中,但因为我注意到您对所使用的键有约束,所以我将其添加到键参数中。您得到的传输文件错误是什么?src/app/dashboard/components/schedule/schedule.component.ts(344,22)中的错误:错误TS2339:类型“UtilitiesService”上不存在属性“setLastPublishedSchedule”。您可以这样调用它:
this.utilService['setLastPublishedSchedule'](此处的参数)
或者您可以在调用它之前将其强制转换为任意
。Transfile错误是因为typesafety,这是typescript存在的一个重要原因。更好的解决方案是添加一个接受字符串并返回某个键的方法。不会破坏类型安全类型脚本是静态类型的。您试图在类上静态使用动态属性。我在以前的项目中使用angularjs添加了setter和getter,方法与我在问题中所问的相同。但我明白用打字脚本做并不更好。根据此答案更改我的代码。谢谢你的时间@Kaushik-很高兴能帮忙!
setValue(key: "CalendarDates"|"LastPublishedSchedule"|"ManageStores"|"SelectedStore", value: string) {
sessionStorage.setItem(key, value);
}
this.utilService.setValue("LastPublishedSchedule", JSON.stringify(response));