【问题标题】:rxjs merge: You provided 'undefined' where a stream was expectedrxjs 合并:您在预期流的位置提供了“未定义”
【发布时间】:2018-11-08 18:19:12
【问题描述】:

我在尝试合并 observbles 时收到错误 You provided 'undefined' where a stream was expected.

我在这里创建我的刷新观察:

refresh$: Observable<Funnel[]>; 

那我有一个计时器...

TimerObservable.create(0, (this.storageService.refRate * 1000))
    .takeWhile(() => this.interval)
    .subscribe(() => {
        this.refresh$ = this.funnelService.getStoryFunnels({}).map(response => [...response]);
    });

然后当我尝试合并 observable 时,就会产生错误:

this.funnels$ = this.funnelService.getStoryFunnels({}).pipe(
    merge(this.refresh$, funnelCreation$.pipe(
            filter(funnel => !!funnel),
            map(funnel => [funnel])
        )
    )
);

根据舒适的回答更新:

this.refresh$ = TimerObservable.create(0, (this.storageService.refRate * 500))
    .takeWhile(() => this.interval)
    .switchMap(() =>  this.funnelService.getStoryFunnels({}).map(response => [...response]));

然后:

this.funnels$ = this.funnelService.getStoryFunnels({}).pipe(
        merge(this.refresh$, funnelCreation$.pipe(
                filter(funnel => !!funnel),
                map(funnel => [funnel])
            )
        )
    );

【问题讨论】:

  • 刚刚意识到您refresh$funnel$ 都依赖于this.funnelService.getStorryFunnels()。你到底想达到什么目的?
  • @CozyAzure 我们正尝试每两分钟更新一次显示。所以 this.funnels 是传递给模板的异步,而 refresh 只是为了更新它。
  • 那么你根本不需要合并。只需将 this.refresh$ 传递给您的模板,它应该可以按预期工作。

标签: angular rxjs


【解决方案1】:

那是因为this.funnels$ 在声明时还不是可观察对象(未使用任何值启动),因为只有在计时器执行后才会为其分配一个值。然而,声明代码几乎立即执行(同步)。这就是为什么您会收到undefined

你应该做的是你可以使用switchMap并将你的this.refresh$分配给它:

this.refresh$ = TimerObservable.create(0, (this.storageService.refRate * 1000))
    .takeWhile(() => this.interval)
    .switchMap(() =>  this.funnelService.getStoryFunnels({}).map(response => [...response]));

【讨论】:

  • 这消除了错误,但我似乎没有看到结果,我应该在网络检查器中的 api 调用中看到它。我会更新上面的代码...
猜你喜欢
  • 2020-03-10
  • 2022-01-17
  • 2020-03-26
  • 2023-04-06
  • 2021-05-21
  • 2021-11-29
  • 2021-12-10
  • 1970-01-01
  • 2019-08-08
相关资源
最近更新 更多