我必须查找是否由于某些路由而刷新或加载了页面。.我认为可以使用有角度的NavigationEnd来实现;订阅路由器事件 有人知道怎么做吗?请不要纯JavaScript解决方案
答案 0 :(得分:1)
当然,您可以像这样使用它:
events
实例上收听Router
的声音。NavigationEnd
。您可以使用Rxjs的filter
运算符来实现它。NavigationEnd
时,您将获得一个事件对象,该事件对象的类型为NavigationEnd
。它具有urlAfterRedirects
和url
之类的属性,您可以利用它们来了解路由操作是否导致导航到特定组件。NavigationEnd
事件。因此,如果发生这种情况,您可以确定是页面被路由到的情况。与此类似:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
@Component({...})
export class YourComponent implements OnInit {
constructor(
..., private router: Router, ...
) { }
ngOnInit() {
...
this.router.events
.pipe(
filter(event => event instanceof NavigationEnd)
)
.subscribe((event: NavigationEnd) => {
console.log('Got the Event URL as ', event.url);
if(event.urlAfterRedirects.includes('project')) {
console.log('This was redirected to the Project Component');
}
});
...
}
...
}
这是您推荐的Sample StackBlitz。
PS:要确认第4点,只需尝试按StackBlitz的View Mode上的重新加载按钮,然后检查控制台上是否打印了任何内容。由于这是重新加载,因此不会打印任何内容。可以将其视为刷新/重新加载情况的确定性。