简体   繁体   English

如何链接 rxjs 可观察对象

[英]How to chain rxjs observables

I'm currently building an Angular header component which makes use of the CDK's Breakpoint Observer to return a string of "mobile", "desktop", or "tablet" according to which breakpoint is currently active.我目前正在构建一个 Angular header 组件,它利用CDK 的断点观察器返回一串“移动”、“桌面”或“平板电脑”,根据哪个断点当前处于活动状态。

I then have a service which uses an RXJS behaviour subject to keep track of which NavLink Id (string value) the user clicked on last.然后我有一个服务,它使用 RXJS 行为主题来跟踪用户最后点击的 NavLink Id(字符串值)。

I'd like to use both the active breakpoint and linkID returned by the service in a single piece of logic like this:我想在单个逻辑中同时使用服务返回的活动断点和链接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; });

This code does work as expected in the browser however when unit testing Jest reports "Test suite failed to run TypeError: Converting circular structure to JSON"此代码在浏览器中按预期工作,但是当单元测试 Jest 报告“测试套件无法运行 TypeError:将循环结构转换为 JSON”时

I believe this is because both the breakpoint observer and the BehaviorSubject used to store the linkID are asynchronous so this.activeBreakpoint will not necessarily have a value when the this.headerService.selectedLinkId.subscribe method is run.我相信这是因为断点观察者和用于存储 linkID 的 BehaviorSubject 都是异步的,所以this.activeBreakpoint在运行this.headerService.selectedLinkId.subscribe方法时不一定有值。 If this is the case is there a way I can chain the two methods to ensure this.activeBreakpoint always has a value?如果是这种情况,有没有办法可以链接这两种方法以确保this.activeBreakpoint始终具有值?

There are many options on chaining observable, you can look at here https://rxjs.dev/guide/operators#join-creation-operators链接 observable 有很多选项,可以看这里https://rxjs.dev/guide/operators#join-creation-operators

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

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