[英]Angular rxjs: Delay subscription till other Observable emits
我有 2 個訂閱 - 一個是我的 ActivatedRoute 的訂閱,另一個是來自 ngrx 商店的訂閱。
ngOnInit() {
this.menuItems$ = this.store.select('menuItems');
this.menuItems$.subscribe(data => {
this.menuItems = data.menuItems;
});
}
ngAfterViewInit() {
this.fragmentSubscription = this.route.fragment.pipe(
filter((fragment: string) => typeof fragment === 'string')
).subscribe((fragment: string) => {
setTimeout(() => {
const element: ElementRef = this.menuItems.find(menuItem => menuItem.link === fragment).element;
if(element !== undefined) {
element.nativeElement.scrollIntoView({ behavior: "smooth", block: "start", inline: "center" });
}
});
});
}
由於我的 ActivatedRoute(片段)訂閱取決於我的商店訂閱數據,我想延遲我的 ActivatedRoute(片段)訂閱,直到我的商店第一次被訂閱
是否有任何 rxjs 運營商為此?
腫瘤壞死因子
根據您的評論...
如果 Store 第一次發出已經完成,我不想再在 ActivatedRoute 訂閱時等待它
您正在尋找combineLatest
,其中...
當任何 observable 發出一個值時,從每個發出最后一個發出的值。
所以我建議如下:
import { Subscription, combineLatest } from 'rxjs';
// ...
mySubscription: Subscription;
ngOnInit() {
this.mySubscription = combineLatest(
this.store.select('menuItems'),
this.route.fragment.pipe(
filter((fragment: string) => typeof fragment === 'string')
)
// DON'T USE ANY, type your data...!
).subscribe((data: [any, any]) => {
this.menuItems = data[0];
const fragment = data[1]
// do your thing...
})
}
ngOnDestroy() {
this.mySubscription.unsubscribe();
}
如果可能,不要從存儲中獲取 init 中的數據。 從解析器中獲取它們。
您當然可以從解析器的商店中獲取它們,然后在 init function 中將它們作為值訪問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.