如何在角度5中显示每个HTTP请求的微调器?

问题描述 投票:4回答:5

我是角度5的新手。如何编写一个通用函数来为角度为5的每个HTTP请求显示微调器。请帮我实现这个。

angular angular-http angular-http-interceptors angular-httpclient
5个回答
9
投票

您可以使用Angular HttpInterceptor来显示所有请求的微调器,这是一个很好的medium article on how to implement an http interceptor

此外,您将必须创建一个微调器服务/模块并将其注入您的http拦截器。最后,在你的拦截方法中,你可以使用finally rxJs方法来阻止你的微调器。这是一个简单的实现:

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this.spinnerService.start();
    return next.handle(req).finally(res => this.spinnerService.stop() );
  }

请享用 !

额外奖励:这是一个spinner service implementation example


2
投票

这与HttpClient或HTTP请求无关。这是一个如何处理异步调用(HTTP或不是)的问题。

你应该有

<div class="spinner" *ngIf="loading"; else showWhenLoaded"><div>
<ng-template #showWhenLoaded>
    <div>Your Content</div>
</ng-template>

并在ts文件中:

loading: boolean = true;

methodToTriggerRequest() {
    this.loading = true;
    this.http.get(...).subscribe(response => {
        if (resposnseNotAnError(response)) {this.loading = false}
    })
}

0
投票

您可以创建服务,然后在订阅它的应用程序的根级别中向其发布事件。让我解释。

broadcast.service.ts(这是你的服务)

import { Injectable } from '@angular/core';

import { Subject } from 'rxjs/Subject';
import { Subscription } from 'rxjs/Subscription';

import 'rxjs/add/operator/filter'
import 'rxjs/add/operator/map'

/**
 * This class acting as event service bus for the entire app.
 * No Need to register the class as this registered in the root level.
 * Can just inject to componets.
 */
@Injectable()
export class BroadcastService {

    private _handler: Subject<Message> = new Subject<Message>();

    broadcast(type: string, payload: any = null) {
        this._handler.next({ type, payload });
    }

    subscribe(type: string, callback: (payload: any) => void): Subscription {
        return this._handler
            .filter(message => message.type === type)
            .map(message => message.payload)
            .subscribe(callback);
    }
}

interface Message {
    type: string;
    payload: any;
}

然后你可以发布和订阅这样的事件:

你的服务水平:

this.broadcastService.broadcast('PROGRESS_START');

在您的应用组件级别:

this.broadcastService.subscribe('PROGRESS_START', ()=>{
  //hit when you start http call
  this.myLoader = true;
});

最后在app.component.html中:

<div *ngIf="myLoader">
 <!--YOUR LOADER SHOULD GO HERE-->
</div>
<router-outlet></router-outlet>

这是一种非常通用的松耦合方式,可以实现您想要的任何加载器。


0
投票

来源Link

创建服务

//loader.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class LoaderService {

  public isLoading = new BehaviorSubject(false);
  constructor() { }
}

创建加载器拦截器

    // loader.interceptors.ts
    import { Injectable } from '@angular/core';
    import {
        HttpErrorResponse,
        HttpResponse,
        HttpRequest,
        HttpHandler,
        HttpEvent,
        HttpInterceptor
    } from '@angular/common/http';
    import { Observable } from 'rxjs';
    import { LoaderService } from './loader.service';

    @Injectable()
    export class LoaderInterceptor implements HttpInterceptor {
        private requests: HttpRequest<any>[] = [];

        constructor(private loaderService: LoaderService) { }

        removeRequest(req: HttpRequest<any>) {
            const i = this.requests.indexOf(req);
            if (i >= 0) {
                this.requests.splice(i, 1);
            }
            this.loaderService.isLoading.next(this.requests.length > 0);
        }

        intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

            this.requests.push(req);
            console.log("No of requests--->" + this.requests.length);
            this.loaderService.isLoading.next(true);
            return Observable.create(observer => {
                const subscription = next.handle(req)
                    .subscribe(
                        event => {
                            if (event instanceof HttpResponse) {
                                this.removeRequest(req);
                                observer.next(event);
                            }
                        },
                        err => {
                            alert('error returned');
                            this.removeRequest(req);
                            observer.error(err);
                        },
                        () => {
                            this.removeRequest(req);
                            observer.complete();
                        });
                // remove request from queue when cancelled
                return () => {
                    this.removeRequest(req);
                    subscription.unsubscribe();
                };
            });
        }
    }

现在创建一个加载器组件,然后添加到app组件中

  //loader.interceptor.ts
  import { Component, OnInit } from '@angular/core';
  import { LoaderService } from '../loader.service';

  @Component({
    selector: 'app-loading',
    templateUrl: './loading.component.html',
    styleUrls: ['./loading.component.css']
  })
  export class LoaderComponent implements OnInit {

    loading: boolean;
    constructor(private loaderService: LoaderService) {
      this.loaderService.isLoading.subscribe((v) => {
        console.log(v);
        this.loading = v;
      });
    }
    ngOnInit() {
    }

  }

-1
投票

在Angular拦截器中,我使用了“to”运算符。

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    // handler for both success and fail response
    const onReqFinish = (event: HttpEvent<any>) => {
      if (event.type === 4) {
        this.onXhrFinish();
      }
    };

    this.onXhrStart();

    return next.handle(req)
     .do(
       onReqFinish,
       onReqFinish
     );
}

onXhrStart函数显示一个加载器和onXhrFinish隐藏它。

整个,工作源代码和演示是here

© www.soinside.com 2019 - 2024. All rights reserved.