Fel
Fel

Reputation: 4818

How to pass extra parameters to RxJS map operator

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,

Upvotes: 2

Views: 2447

Answers (1)

peinearydevelopment
peinearydevelopment

Reputation: 11464

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.

Upvotes: 6

Related Questions