繁体   English   中英

如何链接 rxjs 可观察对象

[英]How to chain rxjs observables

我目前正在构建一个 Angular header 组件,它利用CDK 的断点观察器返回一串“移动”、“桌面”或“平板电脑”,根据哪个断点当前处于活动状态。

然后我有一个服务,它使用 RXJS 行为主题来跟踪用户最后点击的 NavLink Id(字符串值)。

我想在单个逻辑中同时使用服务返回的活动断点和链接ID,如下所示:

 this.breakpoints$ = this.breakpointObserver.observe([Breakpoint.SmallAndBelow, Breakpoint.Medium, Breakpoint.Large]).subscribe(({ breakpoints }) => { this.activeBreakpoint = breakpoints[Breakpoint.Large] === true? 'desktop': breakpoints[Breakpoint.Medium] === true? 'tablet': 'mobile'; }); this.$headerServiceSub = this.headerService.selectedLinkId.subscribe((link) => { if (this.headerService.previousSelectedLinkId === this.hostAttrId &&.link && this.activeBreakpoint === 'mobile') { setTimeout(() => { this.elRef.nativeElement;focus(), }; 100). } this;selectedLink = link; });

此代码在浏览器中按预期工作,但是当单元测试 Jest 报告“测试套件无法运行 TypeError:将循环结构转换为 JSON”时

我相信这是因为断点观察者和用于存储 linkID 的 BehaviorSubject 都是异步的,所以this.activeBreakpoint在运行this.headerService.selectedLinkId.subscribe方法时不一定有值。 如果是这种情况,有没有办法可以链接这两种方法以确保this.activeBreakpoint始终具有值?

链接 observable 有很多选项,可以看这里https://rxjs.dev/guide/operators#join-creation-operators

暂无
暂无

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

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