自定义组件的构造函数中的Param始终未定义

时间:2017-02-20 13:37:40

标签: javascript typescript knockout.js observable custom-component

我在ViewModel中有3个observableArrays;

groupedCustomFields: ko.ObservableArray<any> = ko.observableArray([]);
customFieldsForAdvSearch: ko.ObservableArray<any> = ko.observableArray([]);
countries: ko.ObservableArray<Country> = ko.observableArray([]);

在ViewModel的构造函数中,我使用来自某些API请求的数据

初始化它们
constructor() {
 //some other operations

 this.loadCustomFields();
 this.loadCountries();
}

private loadCustomFieldsForAdvSearch() {
    dataService.Management.getCustomFields()
        .done(response => {
            this.groupedCustomFields(sortBy(new CustomFieldsService().getGroupedFields(response.collection), i => i.displayOrder));
            this.customFieldsForAdvSearch(response.collection
                .filter(l => defaultFields.indexOf(l.name) === -1)
                .map(l => {
                    return {
                        fieldName: l.name,
                        displayName: l.display,
                        displayOrder: l.order,
                        value: ''
                    };
                })
                .sort((x, y) => x.displayOrder - y.displayOrder));
        });
}

private loadCountries() {
    dataService.Management.getCountriesWithStates()
        .done(countries => {
            this.countries(countries);
        });
}

这个observableArrays传递给我的自定义组件:

<component1 params="{
   customFields: customFieldsForAdvSearch,
   groupedCustomFields: groupedCustomFields,
   countries: countries
   }">
</component1>

问题:即使component1groupedCustomFields正常,customFields countries的构造函数也始终未定义。

constructor(params: any) {
   this.customFields = params.customFields;
   this.groupedCustomFields = params.groupedCustomFields;//undefined
   this.countries = params.countries;
}

为什么会这样?我该如何解决?

1 个答案:

答案 0 :(得分:1)

这是你的代码:

<component1 params="{
   customFields: customFieldsForAdvSearch
   groupedCustomFields: groupedCustomFields,
   countries: countries
   }">
</component1>

您的组件调用中缺少逗号,只需添加它就可以了,当您在ViewModel上接收未定义的参数时,这是一个常见问题

<component1 params="{
   customFields: customFieldsForAdvSearch,
   groupedCustomFields: groupedCustomFields,
   countries: countries
   }">
</component1>