[英]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.