我尝试创建一个简单的组件,当路由需要超过半秒才能解析时,该组件的布尔标志isLoading
为true
。
我有一件要把它关掉:
this.router.events
.filter(event => event instanceof NavigationEnd || event instanceof NavigationCancel || event instanceof NavigationError)
.subscribe(event => this.isLoading = false);
但我怎么说:
this.router.events
//given a NavigationStart
//If you don't see NavigationEnd/NavigationCancel/NavigationError within 500ms
.subscribe(event => this.isLoading = true);
答案 0 :(得分:5)
this.router.events
.debounceTime(500)
.filter(event => event instanceof NavigationStart)
.subscribe(event => this.isLoading = true);
这说的是:
.debounceTime(500)
=如果在500毫秒压制我之前创建了另一个事件
.filter(event => event instanceof NavigationStart)
=仅从未遵循500毫秒
.subscribe(event => this.isLoading = true);
=我们现在知道这是一个导航开始,在500毫秒内没有跟踪,所以我们可以开始加载图标
答案 1 :(得分:3)
我刚刚做了这个,没有特殊的计时器:
constructor(private authService: AuthService,
private messageService: MessageService,
private router: Router) {
router.events.subscribe((routerEvent: Event) => {
this.checkRouterEvent(routerEvent);
});
}
checkRouterEvent(routerEvent: Event): void {
if (routerEvent instanceof NavigationStart) {
this.loading = true;
}
if (routerEvent instanceof NavigationEnd ||
routerEvent instanceof NavigationCancel ||
routerEvent instanceof NavigationError) {
this.loading = false;
}
}
它工作正常。如果路线加载很快,则不会出现微调器。如果路径解析器需要一些时间,则会出现微调器。
此代码来自" Angular Routing" Pluralsight课程在这里:https://app.pluralsight.com/library/courses/angular-routing
答案 2 :(得分:1)
我想现在我将采用这个解决方案:
ngOnInit() {
let timer: any;
this.router.events
.subscribe(event => {
if (event instanceof NavigationStart) {
clearTimeout(timer);
timer = setTimeout(() => this.isLoading = true, 250);
} else if (event instanceof NavigationEnd || event instanceof NavigationCancel || event instanceof NavigationError) {
clearTimeout(timer);
this.isLoading = false;
}
});
}
如果有人发布了更清晰的RxJs方式,我会注意到
编辑:基于@KeniSteward的回答,我得到了这个解决方案:
this.router.events
.filter(event => event instanceof NavigationStart || event instanceof NavigationEnd || event instanceof NavigationCancel || event instanceof NavigationError)
.debounceTime(250)
.filter(event => event instanceof NavigationStart)
.subscribe(event => this.isLoading = true);
this.router.events
.filter(event => event instanceof NavigationEnd || event instanceof NavigationCancel || event instanceof NavigationError)
.subscribe(event => this.isLoading = false);
编辑#2 :更清洁 -
this.router.events
.filter(event => event instanceof NavigationStart || event instanceof NavigationEnd || event instanceof NavigationCancel || event instanceof NavigationError)
.do(event => this.isLoading = false)
.debounceTime(250)
.filter(event => event instanceof NavigationStart)
.subscribe(event => this.isLoading = true);
答案 3 :(得分:1)
let isLoading: boolean = false;
ngOnInit() {
this.router.events.subscribe((event) => {
if (event instanceof NavigationStart) {
this.isLoading = true;
}
if (event instanceof NavigationEnd) {
this.isLoading = false;
}
});
}
答案 4 :(得分:0)
每组路由事件都有id。当id被更改时 - 您需要切换微调器。