简体   繁体   English

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

[英]How to pass a property in an angular components as an argument to a private function

I've got an angular component that calls via http to an API to populate a select list.我有一个 angular 组件,它通过 http 调用 API 来填充选择列表。 The property on this component looks like this:此组件上的属性如下所示:

searchKeys: SelectItem[];

And the function that gets the data onInit that works just fine:获取数据 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 };
              });
        });
}

Now, I'd like to turn it into something more generic that I can use for other properties, so something like this:现在,我想把它变成更通用的东西,我可以用于其他属性,所以是这样的:

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

But this doesn't seem to work, where I'm passing 'projectTo' as a reference to the property on my component, it's never populated with values.但这似乎不起作用,我将“projectTo”作为对组件上属性的引用传递,它从未填充值。

What am I missing here?我在这里缺少什么?

According to this answer , Javascript does call by sharing .根据这个答案,Javascript 确实通过共享调用 So the parameter passed is unaffected in your case since you are changing the value of it.因此,传递的参数在您的情况下不受影响,因为您正在更改它的值。

Secondly, observables are asynchronous and so setting of the value within subscribe method may occur after you try to access the data.其次,可观察对象是异步的,因此您尝试访问数据可能会在 subscribe 方法中设置值。 So something like the following which was suggested in the comments is also likely to fail .因此,评论中建议的类似以下内容也可能会失败

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

One way is to return everything as an Observable<any[]> and later subscribe from the common private function.一种方法是将所有内容作为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 });

}

This would allow you to manipulate the array in a generic way without passing any array parameter.这将允许您以通用方式操作数组,而无需传递任何数组参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM