如何将角度组件中的属性作为参数传递给私有函数

时间:2017-10-02 15:41:01

标签: angular typescript

我有一个角度组件,通过http调用API来填充选择列表。此组件的属性如下所示:

searchKeys: SelectItem[];

获取数据onInit的函数运行得很好:

private GetSearchKeyList() {
    this._httpService.get('/api/List/Key')
        .map(result => result.json())
        .subscribe(list => {
            this.searchKeys = list.map(item => { 
                return { label: item.text, value: item.value };
              });
        });
}

现在,我想把它变成更通用的东西,我可以用于其他属性,所以像这样:

this.LoadListValues('/api/List/Key', this.searchKeys);
private LoadListValues(apiEndpoint: string, projectTo: SelectItem[]) {
    this._httpService.get(apiEndpoint)
    .map(result => result.json())
    .subscribe(list => {
        projectTo = list.map(item => { 
            return { label: item.text, value: item.value };
          });
    });
}

但这似乎不起作用,我通过' projectTo'作为对我的组件属性的引用,它从未填充过值。

我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

根据this answer,Javascript通过共享进行调用。因此,在您更改其值时,传递的参数不受影响。

其次,observables是异步的,因此在尝试访问数据之后可能会在subscribe方法中设置值。 因此,评论中建议的以下内容也可能失败

private LoadListValues(apiEndpoint: string, projectTo: SelectItem[]) {
    this._httpService.get(apiEndpoint)
    .map(result => result.json())
    .subscribe(list => {
        list.map(item => { 
            projectTo.push({ label: item.text, value: item.value });
          });
    });
}

一种方法是将所有内容作为Observable<any[]>返回,然后从公共私有函数订阅。

private LoadListValues(apiEndpoint: string):Observable<any[]>{
   return this._httpService.get(apiEndpoint)
    .map(result => result.json())
    .map(list => list.map(item => return { label: item.text, value: item.value });

}

这将允许您以通用方式操作数组,而不传递任何数组参数。