[英]router.events doesn't work properly with async in Angular 6
我正在使用此代碼動態標題
this.router.events.pipe(
filter(event => event instanceof NavigationEnd),
map(() => this.activatedRoute),
map(route => {
while (route.firstChild) {
route = route.firstChild;
}
return route;
}),
filter(route => route.outlet === "primary"),
mergeMap(route => route.data)
).subscribe(data => this.title = data.title || "");
並查看: {{title}}
我想重構這部分(用async
代替subscribe
)所以我做了:
this.title = this.router.events.pipe(
filter(event => event instanceof NavigationEn
mapTo(this.activatedRoute),
map(route => {
while (route.firstChild) {
route = route.firstChild;
}
return route;
}),
filter(route => route.outlet === "primary"),
mergeMap(route => route.data),
pluck("title")
);
並查看: {{title | async}}
{{title | async}}
但是當我通過 URL 打開頁面,甚至刷新頁面時, title
為空。 它僅在我直接在頁面上導航(通過菜單、按鈕等)時才有效。
我不知道為什么它可以與subscribe
一起正常工作,而它不能與async
。
我什至只嘗試使用日志,但這是同樣的問題,標題沒有出現在開頭。
this.title = this.router.events.pipe(
tap(() => console.log("test"));
)
我在 angular 7 中遇到了同樣的問題 - 即想要在this.router.events.pipe
使用async
(而不是subscribe
)。
我使用startWith
( https://www.learnrxjs.io/operators/combination/startwith.html ) 解決了它,因此我可以捕獲初始加載事件以及NavigationEnd
事件。
這是相關的代碼片段:
this.router.events.pipe(
startWith('Initial load'),
filter(event => event === 'Initial load' || event instanceof NavigationEnd),
// rest of code here
);
這聽起來像是一種競爭條件。 在路由器事件完成之前,模板並不總是有機會訂閱。 您可以通過重播路由器事件來處理此問題,以便新訂閱者(如async
指令)接收他們可能錯過的事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.