Skip to content

Instantly share code, notes, and snippets.

@lincolnluiz
Last active October 1, 2017 03:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lincolnluiz/4d882bffe66683c11bf90b3233f041e5 to your computer and use it in GitHub Desktop.
Save lincolnluiz/4d882bffe66683c11bf90b3233f041e5 to your computer and use it in GitHub Desktop.
Angular 2/4 - Tela de carregamento em todas as chamadas ajax
<div class="spinner" *ngIf="loadingService.count > 0" style="cursor: pointer" title="{{ loadingService.count }}"></div>
import { BootstrapGrowlService, BootstrapAlertType } from 'ngx-bootstrap-growl';
import { LoadingService } from './loading.service';
import { Injectable } from '@angular/core';
import { Http, XHRBackend, RequestOptions, RequestOptionsArgs, Request, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/observable/throw';
@Injectable()
export class HttpService extends Http {
constructor(
backend: XHRBackend,
defaultOptions: RequestOptions,
private loadingService: LoadingService) {
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
// exibição da tela de carregamento
this.loadingService.show();
return super.request(url, options)
.map((response: Response) => {
this.loadingService.hide();
return response;
})
.catch((error: Response) => {
this.loadingService.hide();
return Observable.throw(error);
});
}
}
import { Injectable } from '@angular/core';
@Injectable()
export class LoadingService {
public count = 0;
constructor() {
}
show() {
this.count += 1;
}
hide() {
if (this.isLoading()) {
this.count -= 1;
}
}
isLoading(): boolean {
return this.count > 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment