我觉得我的问题与异步编程有关,因为
subscription
在我希望的时候没有运行。我通常把我的问题分为用户视角和开发者视角。
用户视角:
当用户位于主页上并单击 Home 导航按钮时,网站将刷新。用户没有发现这种吸引力并且想要它,如果用户位于主页上并点击主页,那么什么都不会发生。下面是导航图片。如果用户在主页之外,那么(显然)如果他们单击主页,那么他们应该被重定向到主页。
开发者视角:
在模板初始化期间,代码将检查路由器 URL 是否为
/en/home
。如果是 /en/home
,则 href 应等于 #
,如果不是,则 href 应等于 /en/home
。下面提供了注释的代码。
杂项服务:
// service that does miscellaneous things, one of which is just detecting a url change
@Injectable({
providedIn: 'root'
})
export class MiscellaneousService {
urlChange = new Subject<string>()
// other properties & methods
}
标头 TS 组件:
export class HomeHeaderComponent implements OnInit {
currentURL: string = ''
isHomeRoute: boolean = true
constructor(private misService: MiscellaneousService, private router: Router) {}
ngOnInit(): void {
/*
IMPORTANT READ:
on every page, we will do a 'urlChange.next()' method to ensure the currentURL is updated.
I would suppose that the urlChange.next(this.router.url) works but what I am sure of is that the
subscription does not work as currentURL is always an empty string. I would suppose that this has
to do with the asyncronousity of subscribe and when it runs. If that is the case, how can I fix this so that
the component is always updated to the current URL the user is on?
*/
this.misService.urlChange.next(this.router.url)
this.misService.urlChange.subscribe(currentURL => {
this.currentURL = currentURL
})
console.log(this.currentURL)
if (this.currentURL == '/en/home') {
this.isHomeRoute = true
}
else {
this.isHomeRoute = false
}
}
那么我怎样才能让我们订阅
router.url
中的任何更改?我需要改变什么?
如需更多参考,这里是模板的标题部分
标题模板:
<a class="nav-link" [href]="isHomeRoute ? '#' : '/en/home'">
home<span class="sr-only">(current)</span>
</a>
<!-- Other code... -->
您可以观察
router.events
并过滤掉 NavigationEnd
事件以捕获所有成功的路由事件。
router.events
.pipe(
// Only take successfull navigation events
filter((routingEvent) => routingEvent instanceof NavigationEnd),
// Don't forget to clean up your subscriptions
takeUntil(this.destroy$),
)
.subscribe((routingEvent) => {
// Do anything with the URL at this point
console.log(routingEvent.url);
});