由於todo的回答提到,酒吧從0%開始。您需要將其設置爲20%並致電start()
。然而,start()
只是在一定的時間間隔內增加,當它達到100%時,條塊會消失,錯誤地表明加載已完成。如果start()
接受每個步驟調用的回調,這樣會很好,因此您可以將其停止在90%。但事實並非如此。
所以這是我在我們的項目(紅帽自動遷移工具包)做的事:
- 在我們的HTTP服務的包裝(處理的OAuth),我們觸發一個事件,
- ,然後通過抓我們的
LoadingIndicatorService
。
LoadingIndicatorService
- 包裹
SlimLoaderBarService
,
- 並跟蹤有多少HTTP請求中有進展。
- 然後它計算百分比,並將其設置爲20到90%的比例。
- 當所有的HTTP請求完成後,它會在90%左右停留大約一秒鐘,然後調用
complete()
。
如果你必須爲每個導航步驟的多個請求,這看起來很自然,並提供了良好的UX。 如果您通常只有1個請求,那麼您可能需要調整基於CSS的動畫(使其更長)或使用start()
。
以下是一些關鍵的部分代碼:
@Injectable()
export class LoadingIndicatorService {
constructor(
private _slimBarService: SlimLoadingBarService,
private _eventBusService: EventBusService,
) {
// Register the LoadingSomething event listeners.
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 {
// max - counter = finished.
// If the things to load are added after something loaded, the progress would go back.
// But let's rely on that loading will start fast at the beginning.
// Start at 20, jump to 90.
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;
}
有關完整代碼,搜索github.com項目終結。