Whenever a web application performs an async task, such as an HTTP request or animated page transition, it’s a good idea to add a loader animation to improve UX by setting user expectations (i.e. to say, “I’m busy performing a request”).
So we can write a simple “loader” service that does the job in a simple Angular/Ionic application:
import { Injectable } from '@angular/core';
import { LoadingController } from '@ionic/angular';
@Injectable({
providedIn: 'root'
})
export class LoaderProvider {
private loaderElement: HTMLIonLoadingElement;
constructor(private loadingCtrl: LoadingController) {
this.loaderElement = null;
};
public async showLoader() {
this.loaderElement = await this.loadingCtrl.create({
message: "thinking...",
spinner: "crescent"
});
this.loaderElement.present();
};
public hideLoader() {
if (this.loaderElement) {
this.loaderElement.dismiss()
}
};
}
Whenever a component needs a loading indicator to show up, we would import this service into such component through dependency injection (DI) and we would call it as needed, like so:
import { Component } from '@angular/core';
import { LoaderProvider } from '../../services/loader.provider';
import { FoundationProvider } from '../../services/foundation.provider';
@Component({
selector: 'login-modal-component',
templateUrl: 'login.modal.component.html'
})
export class LoginModalComponent {
constructor( public loader: LoaderProvider, private foundation: FoundationProvider ) { }
login(credentials) {
this.loader.showLoader();
this.foundation.login(credentials).subscribe(
success => console.log(success),
error => console.log(error),
() => this.loader.hideLoader()
)
};
}
This works for simple applications but becomes real messy as the app gets bigger, since for every function that potentially requires a “loading spinner” UX we need to deal with show/hide logic in our code.
#rxjs #angular #reactive-programming #rxjs-6 #typescript