TypeScript 从 Enum 创建数组,然后将其用作服务调用的参数



我有一个带有简单服务的角度组件,它根据恰好是枚举的参数提取一些数据。

export enum AgeEnum {
UNDER_18 = 'UNDER_18',
ABOVE_18 = 'ABOVE_18'
}

然后在我的组件中,我有以下内容:

private ageArray = Object.keys(AgeEnum);
private restrictionsWrapper: RestrictionsWrapper;
constructor(private restrictionsService: RestrictionsService) {
}
ngOnInit(): void {
this.getRestrictionsForAge(this.ageArray);
}
private getRestrictionsForAge(ages: string[]) {
for (const age of ages) {
this.restrictionsService.getRestrictions(age as AgeEnum)
.subscribe((options) => {
this.restrictionsWrapper.restrictions = options.restrictions;
}, () => {
this.restrictionsWrapper.restrictions = null;
}
);
}
}

我的 UI 服务如下所示:

getRestrictions(age: AgeEnum): Observable<RestrictionsWrapper> {
const params = new HttpParams().set('age', age);
return this.http.get<RestrictionsWrapper>(BackendRoute.RESTRICTIONS, {params: params});
}

这是我RestrictionsWrapper模型:

export interface RestrictionsWrapper {
restrictionDocuments: string[];
blocked: boolean;
}

所以基本上,根据年龄,我想加载一组不同的"限制"。 但我不想有两个单独的方法,为每个方法传递两个不同的 ENUM 值。我收到一个错误:

Unhandled error occured. TypeError: Cannot set property 'restrictions' of undefined

知道我做错了什么吗?这实际上是正确的(或良好做法(this.restrictionsService.getRestrictions(age as AgeEnum)吗?

那是你的问题,你的RestrictionsWrapper是一个接口。接口仅描述类需要实现的值和函数,但它不是对象。

您的错误消息TypeError: Cannot set property 'restrictions' of undefined尝试告诉您您正在尝试执行以下操作:undefined.restrictions = VALUE

要解决您的问题,您可以在以下两个选项之间进行选择:

第一:

// Initialise your variable with an empty object
private restrictionsWrapper: RestrictionsWrapper = {};

第二:

在组件中:

private restrictionsWrapper: RestrictionsWrapperClass;
constructor(private restrictionsService: RestrictionsService) {
this.restrictionsWrapper = new RestrictionsWrapperClass();
}

例如restriction.api.ts.

export class RestrictionsWrapperClass implements RestrictionsWrapper {
restrictionDocuments: string[];
blocked: boolean;
constructor() {
// Don't know, set some default values if you want
this.restrictionDocuments = [];
this.blocked = false;
}
}

add

restrictionsWrapper = new RestrictionsWrapper();

在控制器的构造函数或 ngOnInit(( 内部或 getLimitsForAge(( 方法中。

发生此错误是因为您尝试在实例化限制包装器之前初始化其属性

最新更新