我试图在route resolver
从数据库获取数据时显示加载图标。
我尝试过以下选项:
根组件:
_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:
<h1 *ngIf="loading">Loading</h1>
加载图标根本不显示。
每次路线更改时,控制台日志中都会显示以下内容:
更新
以下是应用以下更改后的输出:
public loading: boolean = true;
console.log(routerEvent);
console.log("Loading is " + this.loading);
更新2:
app.component.html:
<div class="uk-offcanvas-content">
<h1>{{loading}}</h1>
<h1 *ngIf="loading">Loading</h1>
<app-root-nav></app-root-nav>
<app-notifications></app-notifications>
<router-outlet></router-outlet>
</div>
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
});
}
}
答案 0 :(得分:3)
这里的问题非常简单但容易错过。你不正确地检查路由器事件类型,它应该是:
else if (routerEvent instanceof NavigationError || routerEvent instanceof NavigationCancel || routerEvent instanceof NavigationEnd)
你拥有它的方式只是返回true,因为你的第二个句子基本上是#34;或者如果NavigationCancel是真正的&#34;,它是定义的,因为它是现有的类型。所以当路由解析开始时,立即加载设置为false,因为在NavigationEnd事件之前有很多中间路由器事件,并且由于你的检查方式,所有事件都设置为false。
答案 1 :(得分:0)
尝试使用此代码在路线解析器从数据库获取数据时显示加载图标:
constructor(private router: Router){
router.events.subscribe(e => {
if (e instanceof ChildActivationStart) {
this.loaderservice.show();
} else if (e instanceof ChildActivationEnd) {
this.loaderservice.hide();
}
});
}
答案 2 :(得分:0)
我的情况类似,我通过以下方式解决:
public loading = true;
constructor(private router: Router) {
}
public onClick(): void {
this.loading = true;
this.router.navigate(['/test']).then(_ => {
this.loading = false;
});
}
我以编程方式管理导航。我在开始导航之前将加载变量设置为true
,并在路由完成时将其值切换为false
。