简体   繁体   English

RxJS:shareReplay如何不存储空值?

[英]RxJS: How does shareReplay not store null values ?

let btn = document.getElementById('btn')
let input = document.getElementById('input')

let input$ = defer(() => of(input.value)).pipe(
  tap(v => console.log('tap', v)),
  filter(v => v),
  shareReplay(1)
)
let click$ = fromEvent(btn, 'click').pipe(
  switchMap(_ => input$)
)
click$.subscribe(v => console.log(v))

I just want to store input$ when input value not null. 我只想在输入值不为null时存储input $。 The problem now is that if the input value is null at first, it already store, filter not work. 现在的问题是,如果输入的值最初为null,则它已经存储,过滤器无法正常工作。
demoLink 演示链接

You can try this, make a if-else before the input$ 您可以尝试一下,在输入$之前输入if-else

let btn = document.getElementById('btn')
let input = document.getElementById('input')
if (input != null){
  let inputValue = input
}

let input$ = defer(() => of(inputValue.value)).pipe(
  tap(v => console.log('tap', v)),
  filter(v => v),
  shareReplay(1)
)
let click$ = fromEvent(btn, 'click').pipe(
  switchMap(_ => input$)
)
click$.subscribe(v => console.log(v))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM