Skip to main content

Angular 7: A loading indicator for all API calls.

You users don't like when there is no indication from the application about what is happening. For example when you are loading data from the API and user has no clue about what is happening. I like displaying a small loading icon somewhere at the top to keep the aware about the application state.

To display a small loading indicator at the top of the screen for all API calls untill they return back we can write a small service, an interceptor and a component. I like something like the following




Following is a very simple interceptor
import {Injectable} from '@angular/core';
import {HttpEvent, HttpEventType, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs';
import {tap} from 'rxjs/operators';
import {LoadingService} from './loading.service';

@Injectable()
export class LoadingInterceptor implements HttpInterceptor {
  constructor(private loadingService: LoadingService) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      tap(res => {
        if (res.type === HttpEventType.Sent) {
          this.loadingService.loading$.next(true);
        }

        if (res.type === HttpEventType.Response) {
          this.loadingService.loading$.next(false);
        }
      })
    );
  }
}
Following is extremely simple service which just keep the state of loading indicator as true or false.
import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';

@Injectable({
  providedIn: 'root'})
export class LoadingService {
  public loading$ = new BehaviorSubject(false);
  constructor() {
  }
}
And now a simple component that displays a loading sign at the top-center of the screen.
import {Component, OnInit} from '@angular/core';
import {LoadingService} from '../services/loading.service';

@Component({
  selector: 'amg-loading',
  styleUrls: ['loading.component.scss'],
  template: `<div *ngIf="loading$ | async" class="loader">    <div class="spinner"> Loading      <div class="bounce1"></div>      <div class="bounce2"></div>      <div class="bounce3"></div>    </div>  </div>`})
export class LoadingComponent implements OnInit {
  public loading$;

  constructor(private loadingService: LoadingService) {
    this.loading$ = this.loadingService.loading$;
  }

  ngOnInit() {
  }

}
And finally the css of the component.
.loader {
  z-index: 1000;
  position: absolute;
  top: 0;
  width: 120px;
  margin-left: 50%;
  margin-right: 50%;
  background-color: #ff0f3b;
  color: white}

.spinner {
  text-align: center;
}

.spinner > div {
  width: 12px;
  height: 12px;
  background-color: #333;
  border-radius: 100%;
  display: inline-block;
  -webkit-animation: sk-bouncedelay 1.4s infinite ease-in-out both;
  animation: sk-bouncedelay 1.4s infinite ease-in-out both;
}

.spinner .bounce1 {
  -webkit-animation-delay: -0.32s;
  animation-delay: -0.32s;
}

.spinner .bounce2 {
  -webkit-animation-delay: -0.16s;
  animation-delay: -0.16s;
}

@-webkit-keyframes sk-bouncedelay {
  0%, 80%, 100% { -webkit-transform: scale(0) }
  40% { -webkit-transform: scale(1.0) }
}

@keyframes sk-bouncedelay {
  0%, 80%, 100% {
    -webkit-transform: scale(0);
    transform: scale(0);
  } 40% {
      -webkit-transform: scale(1.0);
      transform: scale(1.0);
    }
}

Comments

Popular posts from this blog

Html5 Canvas Drawing -- Draw dotted or dashed line

This post is for those who want to use html5 canvas for drawing. The canvas API now has built in methods to create lines with dashes. The method is called setLineDash. Following is the code sample to create dashed line. var canvas = document . getElementById ( "canvas" ); var ctx = canvas . getContext ( "2d" ); ctx . setLineDash ([ 5 , 3 ]); /*Dash width and spaces between dashes.*/ ctx . beginPath (); ctx . moveTo ( 0 , 100 ); ctx . lineTo ( 400 , 100 ); ctx . stroke (); If you want to draw lines having a custom style there is no methos in the API. But fortunately there is a way to achieve this. Following is a description about how I achieved this. You can set the stroke pattern on canvas context. Stroke pattern can be created using any image. You create image for your custom pattern and set strokeStyle of the context like the following: var linePattern; imageToUsedAsPattern.onload = function() { linePattern = context.createPattern(imageToU...

Difference between ng-template, ng-content and ng-container

While working on a very complex feature for a client in which I had to present hierarchical dynamic data in three column layout with ability to expand like google image search on each level, I came across ng-content, which seemed like a perfect fit for the solution I was thinking about implementing. But I got confused between ng-content and ng-container when I saw the generated html while debugging my code in developer console. I further investigated both ng-content and ng-container and decided to write my finding here in my blog for future references. If you are also wondering what are they for, read on. <ng-container> When you have to write different host elements to combine many structural component like the following <div *ngIf="condition"> <div *ngFor="..."> Some content here </div> </div> You get many unintentional host elements which are not required for your layout. It becomes a prolem when you have complex appl...

Grouping Exports in Javascript code

As a Javascript developer, you will come across many occassions when you will have to export many functions, variables or other items from one file and import them in different files. You may end up with a code like the following export const function1 = () => { /*something here */ } ; export const function2 = () => { /*something here */ } ; export const function3 = () => { /*something here */ } ; export const function4 = () => { /*something here */ } ; export const function5 = () => { /*something here */ } ; export const function6 = () => { /*something here */ } ; export const function7 = () => { /*something here */ } ; And in the file you want to import you will be importing like the following import { function1, function2, function3, function5, function6, function7 } from './path_to_the_script' You can improve it using * if you want to import all the functions. import * as Functions from './path_to_the_script' This is a better way of imp...