这是我在我们的项目(Red Hat自动迁移工具包)中所做的事情:
- 在我们的HTTP服务包装器(处理OAuth)中,我们触发一个事件,
- 然后被我们的
LoadingIndicatorService
捕获。
LoadingIndicatorService
- 包装了
SlimLoaderBarService
,
- 并跟踪有多少个正在进行的HTTP请求。
- 然后计算百分比,并将其放置在20到90%的比例上。
- 当所有HTTP请求完成时,它会保持在90%左右约一秒钟,然后调用
complete()
。
如果您在每个导航步骤中有多个请求,那么这看起来相当自然,并提供良好的用户体验。
如果您通常只有1个请求,则可以根据CSS动画进行调整(使其更长),或者最终使用start()
。
以下是一些关键代码部分:
@Injectable()
export class LoadingIndicatorService {
constructor(
private _slimBarService: SlimLoadingBarService,
private _eventBusService: EventBusService,
) {
this._eventBusService.onEvent
.filter(event => event.isTypeOf(LoadingSomethingStartedEvent))
.subscribe((event: LoadingSomethingStartedEvent) => this.loadingStarted() )
this._eventBusService.onEvent
.filter(event => event.isTypeOf(LoadingSomethingFinishedEvent))
.subscribe((event: LoadingSomethingFinishedEvent) => this.loadingFinished() )
}
public getSlimService(){
return this._slimBarService;
}
private counter: number = 0;
private max: number = void 0;
private reset() {
this.counter = 0;
this.max = void 0;
}
public loadingStarted(){
this.counter++;
this.max = this.counter;
this.updateProgress();
}
public loadingFinished(){
this.counter--;
this.updateProgress();
}
private updateProgress() {
if (this.counter == 0) {
this._slimBarService.height = "2px";
this._slimBarService.visible = true;
this._slimBarService.progress = 95;
this.max = void 0;
Observable.timer(700).subscribe(() => {
this._slimBarService.complete();
});
}
else {
let percent = 20 + 70 * (1 - (this.max - this.counter) / this.max);
this._slimBarService.height = "3px";
this._slimBarService.color = "#39a5dc";
this._slimBarService.visible = true;
this._slimBarService.progress = percent;
}
}
}
let responseObservable2 = responseObservable.do(
() => console.log("Request SUCCEEDED"),
() => console.log("Request FAILED"),
() => {
console.log("Request FINISHED");
if (this._eventBus) {
console.log("Request FINISHED, firing");
this._eventBus.fireEvent(new LoadingSomethingFinishedEvent(responseObservable))
}
}
);
HTTP服务包装器:
@Injectable()
export class WindupHttpService extends Http {
private configureRequest(method: RequestMethod, f: Function, url: string | Request, options: RequestOptionsArgs = {}, body?: any): Observable<Response> {
let responseObservable: Observable<Response> = ...
...
console.log("Load STARTED");
if (this._eventBus)
console.log("Load STARTED, firing");
this._eventBus.fireEvent(new LoadingSomethingStartedEvent(responseObservable));
return responseObservable2;
}
完整的代码,请搜索Windup项目的github.com。