Angular的路由器——用来标识路由器是执行初始导航还是来自应用



Stack社区你好。

正如问题标题,我想知道是否有一种方法可以识别,Angular中的视图是否被渲染为后续的Angular路由器导航请求(即内部导航请求)

视图是否由于用户在浏览器栏中输入确切的URL而呈现,视图作为应用程序的第一个视图出现?

示例是用户在页面my.page.com/order

上执行某种排序,然后点击这个页面的按钮,将调用router.navigate(['next'])

直接输入my.page.com/order/next到他的URL

我们有一些值得信赖的和生产级的解决方案吗?

你可以监听路由器事件,然后过滤掉所有的导航结束事件,然后成对地发出最后一个值和当前值,然后你把它存储在组件的变量中,或者在一个服务中,然后解决你的问题!

这是从以前的答案,但要点是在加载,你会得到previousPath为null,而当导航发生时,以前的路径将包含一个值!

ngOnInit() {
this.router.events
.pipe(
filter((x) => x instanceof NavigationEnd), // filter out only the navigation end event
startWith(null), // set an initial value
map((x) => x && x.url), // get only the necessary value
pairwise() // emit both the previous and current value
)
.subscribe((event) => {
console.log('navigation succeeded', event[0], event[1]);
this.previousPath = event[0];
this.currentPath = event[1];
});
}

派生stackblitz

最新更新