如何在懒加载期间显示加载组件

3

我在我的Angular项目中进行了惰性加载配置。

虽然这已经完成了,但是出现了一个问题。

因为我的惰性加载组件太大了(700kb),从Web服务器加载组件的时间太长了(0.5秒)。

我必须在惰性加载时显示加载组件。

但是我在Angular路由器模块中找不到加载选项。

我试图查找有关惰性加载的Angular路由器类型定义。

const routes: Routes = [
  { path: '', component: RandingPageComponent },
  {
    path: 'teams/:name',
    // Loading component cannot here
    loadChildren: 'src/app/domain/domain.module#DomainModule'
  },

  { path: '**', component: NotfoundComponent }
];

4
我认为 https://dev59.com/UlgQ5IYBdhLWcg3wSyIO#46423743 可能会对你有帮助。 - Sumeet Kale
1
不必显示加载,可以预加载模块:https://vsavkin.com/angular-router-preloading-modules-ba3c75e424cb - ibenjelloun
2个回答

3

Router.navigate方法返回一个promise。因此您可以在其上调用then()。因此您可以保持一个名为showLoadingComponent的变量,默认为false,并在您导航时执行此操作:

this.showLoadingComponent = true;
this.router.navigate(['/newComponent']).then(value => {
      this.showLoadingComponent = false;
});

在您的 HTML 中,
<div *ngIf="!showLoadingComponent">
    // default content
</div>
<appLoadingComponent *ngIf="showLoadingComponent"></appLoadingComponent>

点击导航到懒加载组件后,此代码将显示您的加载组件,直到懒加载组件加载完成。

1
正如你在 https://angular.io/api/router/Router 所看到的那样,“navigate”方法返回的不是“Observable”,而是“Promise”。不过,你使用了正确的方法来接收通知——“then”。 - Buczkowski

2

试试这个(app.component.ts)

import { Component } from "@angular/core";
import { Router, NavigationStart, NavigationEnd, Event, NavigationCancel, 
NavigationError } from "@angular/router";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"]
})
export class AppComponent {
  public showLoadingIndicator: boolean = true;
  constructor(private _router: Router) {
    this._router.events.subscribe((routerEvent: Event) => {
      if (routerEvent instanceof NavigationStart) {
        this.showLoadingIndicator = true;
      }

      if (routerEvent instanceof NavigationEnd ||
        routerEvent instanceof NavigationCancel ||
        routerEvent instanceof NavigationError) {
        this.showLoadingIndicator = false;
      }
    });
  }
}

最初的回答:
在 HTML 中 (app.component.ts)
<div *ngIf="showLoadingIndicator" class="loading">Loading&#8230;</div>
<router-outlet></router-outlet>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接