问题
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