在 Angular 2 中加载延迟加载的模块时显示活动指示器 [英] Show activity Indicator while loading a lazy loaded Module in Angular 2

查看:22
本文介绍了在 Angular 2 中加载延迟加载的模块时显示活动指示器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My scenario is as follows. I have a menu, with multiple options. Each menu should be shown depending on user permissions (already solved), most menu items are encapsulated as modules, and most of the modules are lazy loaded, so when a user clicks a menu item the first time, it loads (up to here everything works well), now my requirement is, in order to give a better user experience, I need to show activity indicator after user clicks a menu item while the lazy loaded module is loading.

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

Up to this, I tried using canActive, canLoad, canActivateChild interfaces from Angular Router but with no luck.

有什么想法吗?

推荐答案

你可以监听两个路由器事件:

You can listen for two router events:

  • RouteConfigLoadStart
  • RouteConfigLoadEnd

它们在加载延迟加载的模块时触发.与标准路由事件(例如 NavigationStart)相比,使用这些事件的优势在于它们不会在每次路由更改时触发.

They fire when a lazy loaded module is being loaded. The advantage of using these over the standard router events such as NavigationStart is that they won't fire on every route change.

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

Listen to them in your root AppComponent to show / hide your spinner.

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;
            }
        });
    }
}

app.component.html

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

Just a simple string here, but you could use a spinner component.

<router-outlet></router-outlet>

<ng-container *ngIf="loadingRouteConfig">Loading route config...</ng-container>

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

I'm using this approach with Angular v4.2.3

这篇关于在 Angular 2 中加载延迟加载的模块时显示活动指示器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆