How to pass extra parameters to RxJS map operator

妖精的绣舞 提交于 2021-02-10 17:47:46

问题


In an Angular app, I use HttpClient and RxJS operators to make some API calls. For example:

return this.httpClient.put(url, JSON.stringify(treeOptions))
        .pipe(
        map(this.extractTreeData),
        catchError(this.handleError)
        );

The extractTreeData method basically changes some properties returned by the API:

private extractTreeData(res: any) {
    let apiTree = res.data;  // The tree comes inside the 'data' field
    let newTree : any;

    try {
        let str = JSON.stringify(apiTree);

        str = str.replace(/"children"/g, '"items"');
        str = str.replace(/"allowdrag"/g, '"allowDrag"');

        newTree = JSON.parse(str);        
    } catch(e) {
        // Error while parsing
        newTree = null;
    }

    return newTree || {};
}

I need to do some more changes depending on the type of tree. How could I pass this type to the mapped method? I mean:

[...]
.pipe(
  map(this.extractTreeData), <== HOW TO PASS VARIABLE 'treeType' TO extractTreeData
[...]

Thanks in advance,


回答1:


The line

map(this.extractTreeData)

is the equivalent of

map(tree => this.extractTreeData(tree))

If you use the expanded form, you can then update it to pass more parameters as follows:

map(tree => this.extractTreeData(tree, treeType))

It is hard to give you a full answer though as you don't show where treeType is coming from.



来源:https://stackoverflow.com/questions/53500562/how-to-pass-extra-parameters-to-rxjs-map-operator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!