startWith 发生在您过滤了您的内容之后。
of(1).pipe( // will yield (1)
filter(_ => false), // will yield ()
startWith('hello') // will yield ('hello')
).susbcribe(val => console.log(val));
因此,包含1 的流经过过滤以不让任何东西通过它本身就是一个东西。然后用startWith 操作符“修饰”那个东西,这使它产生一个初始的hello。
那个新的流就是你订阅的流!
这确实是预期的行为。
让startWith 在pipe(...) 参数中高于filter,你会看到它是如何变化的:
of(1).pipe( // will yield (1)
startWith('hello'), // will yield ('hello', 1)
filter(_ => false) // will yield ()
).susbcribe(val => console.log(val));
要解决 cmets 部分中的问题,您可以将pipe 链视为nested calls。例如,在伪代码中:
A.pipe(B, C, D)
... 相当于做:
D(C(B(A)))
因此,以下内容:
of(1).pipe( // expression A
filter(_ => false), // expression B
startWith('hello') // expression C
).susbcribe(val => console.log(val));
... 将转换为:
startWith( // expression C
filter( // expression B
of(1), // expression A
_ => false
),
'hello'
).susbcribe(val => console.log(val))
或者,以更“必要”的方式:
const one = of(1);
const filtered = filter(one, _ => false);
const greeted = startWith(filtered, 'hello');
greeted.subscribe(val => console.log(val));
很明显,过滤器不会影响更下游的操作员!