在Angular 2中加载延迟加载的模块时显示活动指示器

vic*_*mac 28 lazy-loading angular2-routing angular

我的方案如下.我有一个菜单,有多个选项.应该根据用户权限(已经解决)显示每个菜单,大多数菜单项都封装为模块,并且大多数模块都是延迟加载的,因此当用户第一次单击菜单项时,它会加载(到此为止所有内容)效果很好),现在我的要求是,为了提供更好的用户体验,我需要在加载延迟加载的模块时用户点击菜单项后显示活动指示器.

到目前为止,我尝试使用canActive,canLoad,来自Angular Router的canActivateChild接口,但没有运气.

有任何想法吗?

Dan*_*isp 60

您可以侦听两个路由器事件:

  • RouteConfigLoadStart
  • RouteConfigLoadEnd

它们在加载延迟加载的模块时触发.使用这些优于标准路由器事件的优点NavigationStart是,它们不会在每次路由更改时触发.

在您的根AppComponent中收听它们以显示/隐藏您的微调器.

app.component.ts

import { Router, RouteConfigLoadStart, RouteConfigLoadEnd } from '@angular/router';

...

export class AppComponent implements OnInit {

    loadingRouteConfig: boolean;

    constructor (private router: Router) {}

    ngOnInit () {
        this.router.events.subscribe(event => {
            if (event instanceof RouteConfigLoadStart) {
                this.loadingRouteConfig = true;
            } else if (event instanceof RouteConfigLoadEnd) {
                this.loadingRouteConfig = false;
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

app.component.html

这里只是一个简单的字符串,但您可以使用微调器组件.

<router-outlet></router-outlet>

<ng-container *ngIf="loadingRouteConfig">Loading route config...</ng-container>
Run Code Online (Sandbox Code Playgroud)

我在Angular v4.2.3中使用这种方法

  • 这样可以显示文本,但是,如果您使用微调器或CSS动画等东西,则一旦模块开始加载,动画就会停止(尽管显示了动画组件本身,但冻结在了框架上)。请注意,旋转器本身不是问题,仅在模块加载时才存在。 (3认同)
  • 如果您使用 PreloadAllModules 策略,那么这也将显示在后台加载的所有模块。在这种情况下,最好同时捕获 NavigationStart 和 NavigationEnd 并忽略这些事件之外的 RouteConfigLoadStart 和 RouteConfigLoadEnd。 (2认同)

tan*_*dar 24

你可以这样做

  1. 在app.component.html中
<div class="main-loader" *ngIf="loading">
  <div class="cssload-container" >
      <div class="cssload-whirlpool"></div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)
  1. 在app.component.ts中

    import { Router, NavigationStart, NavigationEnd } from '@angular/router';
    
    
    loading:boolean = false;
    constructor(private router:Router) { 
      router.events.subscribe(event => {
        if(event instanceof NavigationStart) {
          this.loading = true;
          console.log("event started")
        }else if(event instanceof NavigationEnd) {
          this.loading = false;
          console.log("event end")
        }
        // NavigationEnd
        // NavigationCancel
        // NavigationError
        // RoutesRecognized
      });
    
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在css任何加载动画

希望这对你有用.谢谢


You*_*esM 1

你可以只使用CSS!

<routler-outlet></routler-outlet>
<div class='.loader>
  Just, wait a sec ! I'm loading
</div>
Run Code Online (Sandbox Code Playgroud)

在你的模板中

router-outlet + .loader {
  opacity : 1;
}

.loader {
  opacity : 0;
}
Run Code Online (Sandbox Code Playgroud)

然后您可以使用 HTML/CSS 创建精美的旋转器