链式Map操作符未传参数?Angular代码实现疑问
map(this.extractData) Works in RxJS Great question! Let’s break down this common RxJS pattern you’re seeing in your Hyperledger Composer Angular app.
First, let’s recall what RxJS’s map operator does: it takes a transformation function as an argument. Every time a value (in this case, the HTTP Response object from this.http.post) flows through the observable stream, map calls this function with that value as the first parameter, then emits the function’s return value as the new stream value.
Why passing a function reference works
When you write .map(this.extractData), you’re not calling the extractData function immediately—you’re passing a reference to it. RxJS’s map operator will handle invoking the function later, automatically passing the current Response object as the argument. This is exactly equivalent to writing:
.map(res => this.extractData(res))
The only difference is that passing the function reference is more concise when your transformation logic is already encapsulated in a separate method.
A note on this context
You might be wondering if using the function reference could break the this keyword inside extractData. In your specific code, this isn’t a problem because extractData doesn’t use this at all—it only operates on the res parameter passed to it.
If extractData did need to access class properties or methods (e.g., this.someProperty), then directly passing this.extractData would cause issues, because the function’s this context would no longer point to your service instance. In that case, you’d need to preserve the context using either:
- An arrow function:
.map(res => this.extractData(res)) Function.bind():.map(this.extractData.bind(this))
Your code in context
Looking at your extractData method:
private extractData(res: Response): any { return res.json(); }
Since it only depends on the incoming res parameter and doesn’t interact with other parts of your service, using .map(this.extractData) is a perfectly valid, clean approach—it’s actually a common best practice for separating repeated transformation logic into reusable methods.
内容的提问来源于stack exchange,提问作者Olegario

