【问题标题】:how to show loading animation before element is shown in angular如何在元素以角度显示之前显示加载动画
【发布时间】:2022-03-11 02:35:48
【问题描述】:

我正在通过 Angular 服务获取一些数据,大约需要 2-3 秒才能出现。因此与该服务对应的 HTML 元素也需要时间来加载。有没有办法显示特定元素的加载动画?

【问题讨论】:

  • 控制器:loading = true; this.service.get().subscribe(res => { this.loading = false; ...});。模板:<ng-container *ngIf="loading; else elseBlock>Loading...</ng-container><ng-template #elseBlock>...</ng-template>.
  • 您可以使用布尔值来跟踪组件的状态,然后使用 *ngIf 有条件地根据该状态呈现 HTML

标签: javascript jquery angular


【解决方案1】:

你可以使用 RxJs 中的 finalize 操作符 https://www.learnrxjs.io/learn-rxjs/operators/utility/finalize

getData() {
  this.showLoader = true;
  this.service.getYourObs().pipe(finalize(() => this.showLoader = false)).subscribe(...);
}

【讨论】:

    【解决方案2】:

    您需要跟踪加载状态并让模板做出相应反应。

    如果您不使用 @ngrx/store 之类的东西,请在您的组件中添加一个变量。

    isLoading = false

    获取数据时,更改该变量...

    getSomeData(){
      this.isLoading = true;
      
      this.service.getSomeData().subscribe((data) => {
        //... Do stuff with data
        this.isLoading = false;
      })
    }
    

    ...然后在您的模板中...

    <ng-container *ngIf="!isLoading; else loader">
      <!-- Visible if not loading -->
    </ng-container>
    <ng-template #loader>
      <!-- Loader element -->
    </ng-templtate>
    

    请注意,这是一个非常简单的示例,通常可以通过某种状态管理更好地处理。

    【讨论】:

    • 正如我的回答所说,我相信使用 finalize 更合适,因为无论订阅是否成功,布尔值都将设置为 false。在您的回答中,如果 getSomeData() 失败,布尔值将永远不会被重置
    • 是的,我不反对,因此我免责声明这是一个非常基本的例子。我的目标是朝着正确的方向前进,而不是提供彻底的完整解决方案。
    【解决方案3】:

    你只需要知道请求是否完成并根据它设置loading标志。

    AppComponent HTML

    <ng-container>
     <loading-el *ngIf = "loading"></loading-el>
     <main-components *ngIf = "!loading"></main-components>
    </ng-container>
    

    Appcomponent.ts

    loading = false;
    
    getRecord() {
     this.loading = true;
     this.http.get(rec => {
      this.loading = false;
      ...operation...
     })
    }
    

    【讨论】:

      【解决方案4】:

      这是一个非常标准的要求,您有一些选择。

      最简单的方法是在组件上创建一个布尔属性,并在 ngOnit 挂钩中将其设置为 true。这是一个逐步完成的链接。

      How to show spinner in angular 6

      ...作为替代方案,您可以编写一个角度解析器来在加载组件之前获取您的数据。

      https://dzone.com/articles/understanding-angular-route-resolvers-by-example#:~:text=A%20Resolver%20is%20a%20class,may%20also%20like%3A%20Angular%20Resolvers.

      两者都需要某种加载器图形,解析器允许您在应用程序级别处理加载,从而停止组件中的重复。

      【讨论】:

        【解决方案5】:

        您实际上不需要在组件级别管理标志。

        使用可观察对象。

        import { Component, OnInit } from '@angular/core';
        import { from, Observable } from 'rxjs';
        
        class Item {
          constructor(public name = 'New Item') {}
        }
        
        @Component({
          selector: 'my-app',
          template: `
            <button (click)="loadItems()">Load</button>
            <hr>
            <ng-container *ngIf="items$ | async as items; else loading">
              <div *ngFor="let item of items; let index = index">
                {{index+1}}. {{ item.name }}
              </div>
            </ng-container>
            <ng-template #loading>
              Loading...
            </ng-template>
          `,
        })
        export class AppComponent implements OnInit {
          items$: Observable<Item[]>;
        
          ngOnInit() {
            this.loadItems();
          }
        
          private loadItems() {
            // Simulate HTTP request
            const promise: Promise<Item[]> = new Promise((resolve) => {
              setTimeout(() => {
                resolve([new Item(), new Item(), new Item()]);
              }, 750);
            });
        
            // Where the magic happens
            // Reassign the observable, which will trigger the else
            // block in the template and display the loader.
            // Once it completes, it will display the list as normal.
            this.items$ = from(promise);
          }
        }
        
        

        【讨论】:

          猜你喜欢
          • 2022-01-10
          • 2022-10-23
          • 1970-01-01
          • 2021-05-07
          • 2020-07-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-26
          相关资源
          最近更新 更多