代码之家  ›  专栏  ›  技术社区  ›  lapadets

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

  •  0
  • lapadets  · 技术社区  · 8 年前

    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;
                    }
                );
        }
    }
    

    我的用户界面服务如下所示:

    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;
    }
    

    但我不想有两个单独的方法,在这里我为每个方法传递两个不同的枚举值。我发现一个错误:

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

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

    2 回复  |  直到 8 年前
        1
  •  1
  •   Batajus    8 年前

    这是你的问题 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;
        }
    
    }
    
        2
  •  1
  •   Ranjith Eswaran    8 年前

    添加

    restrictionsWrapper = new RestrictionsWrapper();
    

    发生此错误是因为您在实例化restrictionsWrapper之前尝试初始化它的属性