Skip to content

Instantly share code, notes, and snippets.

@limenutt
Last active April 5, 2021 07:36
Show Gist options
  • Save limenutt/8784829c3e2ee8047a9b7d132e7af690 to your computer and use it in GitHub Desktop.
Save limenutt/8784829c3e2ee8047a9b7d132e7af690 to your computer and use it in GitHub Desktop.
A naive Angular service to track the loading state
// from LinkedIn thread
// https://bit.ly/3up4oeK
@Injectable({
providedIn: 'root',
})
export class LoadingService {
private _loading = new BehaviorSubject<boolean>(false);
private _pendingOperations = 0;
protected get pendingOperations(): number {
return this._pendingOperations;
}
protected set pendingOperations(operations: number) {
if (operations > 0) {
this._pendingOperations = operations;
} else {
if (operations < 0) {
console.warn(`We have an inconsistency in the pending operations count [${operations}]`)
}
this._pendingOperations = 0;
}
this._loading.next(this._pendingOperations === 0);
}
public readonly loading$ = this._loading.asObservable();
/**
* Add a loading operation to the queue
*/
public enqueue() {
this.pendingOperations++;
}
/**
* Removes a loading operation from the queue
*/
public dequeue() {
this.pendingOperations--;
}
}
@Component({
selector: 'sample-component',
templateUrl: './sample.component.html',
styleUrls: ['./sample.component.scss'],
})
export class SampleComponent {
constructor(protected loadingService: LoadingService) { }
async loadData(): Promise<void> {
this.loadingService.enqueue();
try {
// data loading code here
} finally {
this.loadingService.dequeue();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment