如何为Angular 17懒加载路由显示加载状态?
在Angular 17懒加载授权路由时显示加载进度,解决登录后UI异常
问题分析
登录后跳转至/dashboard时,懒加载app-authorized.routes.ts的代码块存在延迟,导致登录组件未及时隐藏但授权导航栏已显示,出现UI冲突。通过监听路由懒加载的开始/结束事件,我们可以在加载过程中显示加载层,覆盖旧UI,避免异常。
实现步骤
1. 创建加载组件
先实现一个简单的全屏加载组件,用于显示加载状态:
// loading.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-loading', standalone: true, // 独立组件配置 template: ` <div class="loading-overlay"> <div class="spinner"></div> <p>加载中,请稍候...</p> </div> `, styles: [` .loading-overlay { position: fixed; inset: 0; background-color: rgba(255, 255, 255, 0.9); display: flex; flex-direction: column; align-items: center; justify-content: center; z-index: 9999; } .spinner { width: 60px; height: 60px; border: 6px solid #e0e0e0; border-top-color: #1976d2; border-radius: 50%; animation: spin 1.2s linear infinite; } @keyframes spin { to { transform: rotate(360deg); } } `] }) export class LoadingComponent {}
2. 在根组件监听路由事件
在AppComponent中监听路由的RouteConfigLoadStart和RouteConfigLoadEnd事件,控制加载组件的显示:
// app.component.ts import { Component } from '@angular/core'; import { Router, RouteConfigLoadStart, RouteConfigLoadEnd } from '@angular/router'; import { LoadingComponent } from './loading/loading.component'; @Component({ selector: 'app-root', standalone: true, imports: [LoadingComponent], template: ` <app-loading *ngIf="isLoading"></app-loading> <router-outlet></router-outlet> `, }) export class AppComponent { isLoading = false; constructor(private router: Router) { this.router.events.subscribe(event => { if (event instanceof RouteConfigLoadStart) { this.isLoading = true; } else if (event instanceof RouteConfigLoadEnd) { this.isLoading = false; } }); } }
3. 优化登录跳转逻辑
确保登录成功后立即触发路由跳转,此时路由事件会自动捕获懒加载状态:
// login.component.ts import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { AuthService } from './auth.service'; @Component({ selector: 'app-login', standalone: true, template: ` <!-- 登录表单 --> <button (click)="login()">登录</button> ` }) export class LoginComponent { constructor(private authService: AuthService, private router: Router) {} login() { // 模拟登录请求 this.authService.login().subscribe(() => { // 登录成功后跳转至dashboard this.router.navigate(['/dashboard']); }); } }
效果说明
当登录成功跳转时,路由开始懒加载app-authorized.routes代码块,RouteConfigLoadStart事件触发,加载组件全屏显示,覆盖登录组件;加载完成后RouteConfigLoadEnd事件触发,加载组件隐藏,正常显示DashboardComponent及授权导航栏,彻底解决UI异常问题。
内容的提问来源于stack exchange,提问作者Chris Barr
相关产品推荐
相关产品推荐

