簡體   English   中英

Angular 加載攔截器

[英]Angular loading interceptor

如何在 angular 加載攔截器中避免多次加載在 angular 中,每個 http 調用加載微調器並嘗試只為初始頁面加載實現一次加載。 如何解決這個問題

您正在處理現有的 Angular 應用程序。

該應用程序使 HTTP 從許多不同的組件調用 REST API。

您想為每個 HTTP 請求顯示一個自定義微調器。 由於這是一個現有的應用程序,有很多地方調用了 REST API。 並且在每個地方一個一個地更改代碼並不是一個可行的選擇。

所以,你想實現一個抽象的解決方案來解決這個問題。

代碼可以寫得更簡單,無需在 memory 中創建新的 observable 和存儲請求。 下面的代碼還使用帶有管道運算符的 RxJS 6:

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpInterceptor,
  HttpResponse
} from '@angular/common/http';
import { finalize } from 'rxjs/operators';
import { LoadingService } from '@app/services/loading.service';
import { of } from 'rxjs';

@Injectable()
export class LoadingInterceptor implements HttpInterceptor {
  private totalRequests = 0;

  constructor(private loadingService: LoadingService) { }

  intercept(request: HttpRequest<any>, next: HttpHandler) {
    this.totalRequests++;
    this.loadingService.setLoading(true);

    return next.handle(request).pipe(
      finalize(res => {
        this.totalRequests--;
        if (this.totalRequests === 0) {
          this.loadingService.setLoading(false);
        }
      })
    );
  }
}

將此攔截器服務添加到您的模塊提供程序中:

@NgModule({
  // ...
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: LoadingInterceptor, multi: true }
  ]
})
export class AppModule { }

這是LoadingService實現的示例:

@Injectable()
export class LoadingService {
  private isLoading$$ = new BehaviorSubject<boolean>(false);
  isLoading$ = this.isLoading$$.asObservable();
  
  setLoading(isLoading: boolean) {
    this.isLoading$$.next(isLoading);
  }
}

以下是您在組件中使用LoadingService的方式:

@Component({
  selector: 'app-root',
  template: `
    <ng-container *ngIf="loadingService.isLoading$ | async">
      <i class="loading"></i>
    </ng-container>
    <router-outlet></router-outlet>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {
  constructor(public loadingService: LoadingService) {}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM