我对Angular 5还不熟悉。如何编写通用函数以在Angular 5中为每个HTTP请求显示加载动画?请帮助我实现此功能。
我对Angular 5还不熟悉。如何编写通用函数以在Angular 5中为每个HTTP请求显示加载动画?请帮助我实现此功能。
您可以使用Angular的HttpInterceptor为所有请求显示一个旋转器。以下是一篇不错的Medium文章,介绍如何实现http拦截器。
另外,您需要创建一个Spinner服务/模块并将其注入到您的http拦截器中。最后,在您的拦截方法中,您可以使用finally
rxJs方法停止旋转器。以下是一个简单的实现:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.spinnerService.start();
return next.handle(req).finally(res => this.spinnerService.stop() );
}
享受吧!
奖励:这里是一个 加载动画服务实现示例
来源 链接
创建一个服务
//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 拦截器
// 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();
};
});
}
}
//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() {
}
}
<div class="spinner" *ngIf="loading"; else showWhenLoaded"><div>
<ng-template #showWhenLoaded>
<div>Your Content</div>
</ng-template>
loading: boolean = true;
methodToTriggerRequest() {
this.loading = true;
this.http.get(...).subscribe(response => {
if (resposnseNotAnError(response)) {this.loading = false}
})
}
您可以在应用程序的根级别订阅服务并向其发布事件。让我解释一下。
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>
这是一种非常通用的松耦合方式,可以实现任何你想要的加载器。
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';
import { NgxSpinnerService } from 'ngx-spinner';
@Injectable()
export class SpinnerInterceptor implements HttpInterceptor {
constructor(private spinner: NgxSpinnerService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.spinner.show();
return next.handle(req).pipe(
finalize(() => this.spinner.hide())
);
}
}
在应用程序模块中提供此服务
import { HTTP_INTERCEPTORS } from '@angular/common/http';
....
@NgModule({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: SpinnerInterceptor, multi: true }
]
})
在 app.component 中,在 router-outlet 内添加您的 spinner 标签
<router-outlet>
<ngx-spinner bdColor="rgba(0,0,0,0.8)"
size="medium"
color="#fff"
type="timer">
<p style="color: #fff"> Loading... </p>
</ngx-spinner>
</router-outlet>
正如您所看到的,我正在使用NgxSpinner,但如果您使用自定义旋转器,则不应有任何区别,您只需要创建服务来显示和隐藏旋转器,并将此服务注入旋转器拦截器中。
在这里,我写了一些步骤来创建自己的自定义进度条。
创建一个组件
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-sw-progressbar',
template: <div *ngIf="loading">
<mat-progress-bar style="position:absolute; left:15px; width: calc(100% -
30px); height:5px;"
color="primary"
mode="indeterminate">
</mat-progress-bar>
</div>
,
})
export class SWProgresbarComponent {
@Input() loading = false;
constructor() { }
}
2 在模块中导入组件:
import { SWProgresbarComponent } from '../sw-progressbar.component';
@NgModule({
declarations: [SWProgresbarComponent],
imports: [
CommonModule,
MaterialModule,
RouterModule
],
exports: [SWProgresbarComponent,
RouterModule
]
})
export class SharedModule { }
如何使用?
在你想要显示加载器的组件中,loading将为真。在该组件中添加以下代码:
<app-sw-progressbar [loading]="loading"></app-sw-progressbar>
如果要使用旋转图标,则将mat-progress-bar替换为mat-progress-spinner。
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函数隐藏它。
完整的工作源代码和演示在这里。