帮助我理解这段代码,尽管of (1,2,3)
map( x => x*x)
在代码行中按第 1 次排序,of (1,2,3)
如何通过管道传输到map( x => x*x)
map(x => x*x) (of (1,2,3)).subscribe((value)=> console.log(`value : ${value}`))
同样可以写成下面,我理解得很好,但不高于一个..
of(1,2,3).pipe(map(x => x*x)).subscribe((value)=> console.log(`value : ${value}`))
仅供参考,两者都是正确的,并且返回值 1,4,9
如果您在编辑器中尝试相同的操作,请包含以下导入
import {of} from 'rxjs'
import {map} from 'rxjs/operators'
这实际上是 RxJS 文档中的一个例子,上面有解释:
管道运算符本质上是一个纯函数,它将一个可观察量作为输入并生成另一个可观察量作为输出。订阅输出可观察量也将订阅输入可观察量。
所以这意味着map(x => x*x)
返回一种函数,它将一个可观察量作为参数并返回另一个可观察量。然后我们使用(of(1,2,3))
调用该函数并得到我们的最终结果,实际上等于of(1,2,3).pipe(map(x => x*x))
它更像是一个JavaScript功能。如果您看到函数像foo()()
或foo() ('hello')
一样调用,则表示foo正在返回另一个函数,并且第二个"(("中的参数(如foo() ('hello')
中的"hello"(被传递给foo((返回的函数。
示例将以下代码另存为示例
.js,并使用node sample
执行它
foo()() // return undefined, as empty parameter ( parenthesis ) are passed though expecting one
foo()('hello') // param 'hello' is passed to bar when it is returned inside foo
foo()('hello','world') //both hello and world are passed, but only hello is printed, as bar expect only 1 param
function foo() {
return bar
}
function bar (param) {
console.log('bar : '+param)
}
结果
bar : undefined
bar : hello
bar : hello