我尝试过以下选项:
根组件:
_router.events.subscribe((routerEvent: RouterEvent) => {
if (routerEvent instanceof NavigationStart) {
console.log("start");
this.loading = true;
} else if (routerEvent instanceof NavigationError || NavigationCancel || NavigationEnd) {
console.log("end");
this.loading = false;
}
});
根组件HTML:
加载图标根本不显示.
更新:
以下是应用以下更改后的输出:
public loading: boolean = true;
console.log(routerEvent);
console.log("Loading is " + this.loading);
更新2:
app.component.html:
app.component.ts:
import {Component,OnInit,AfterViewInit} from '@angular/core';
import {AuthenticationService} from "../../authentication/services/authentication.service";
import {Router,Event,NavigationStart,NavigationEnd,NavigationCancel,NavigationError} from "@angular/router";
import {RouterEvent} from "@angular/router";
import UIkit from 'uikit'
@Component({
selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit,AfterViewInit {
isLoggedIn: boolean;
public loading: boolean = true;
UIkit: any;
constructor(private _router: Router,private _authService: AuthenticationService) {
_router.events.subscribe((routerEvent: RouterEvent) => {
if (routerEvent instanceof NavigationStart) {
this.loading = true;
console.log(routerEvent);
console.log("Loading is " + this.loading);
} else if (routerEvent instanceof NavigationError || NavigationCancel || NavigationEnd) {
this.loading = false;
}
});
}
ngAfterViewInit() {
}
ngOnInit() {
UIkit.notification({
message: 'my-message!',status: 'primary',pos: 'top-right',timeout: 5000
});
}
}
最佳答案
这里的问题非常简单但容易错过.你不正确地检查路由器事件类型,它应该是这样的:
else if (routerEvent instanceof NavigationError || routerEvent instanceof NavigationCancel || routerEvent instanceof NavigationEnd)
你拥有它的方式只是返回true,因为你的第二个子句基本上是“或者如果NavigationCancel是真的”,它是定义的,因为它是一个现有的类型.因此,当路由解析开始时,立即加载设置为false,因为在NavigationEnd事件之前有很多中间路由器事件,并且由于您正在检查的方式,所有事件都设置为false.