Show a loading gif for each http request Angular 4

Viewed 50753

I'm quite new with Angular so what I need is to show a spinner each time when a http request is done.

I have many components:

<component-one></component-one>
<component-two></component-two>
<component-three></component-three>
<component-n></component-n>

Each one has a http request that get or save some data so when the http request is made I want to show my <loading></loading> component so I suppose is not a good practice injecting my loading component in each other component with a http request. Can I add a filter or something from angular that allows me to load the <loading> component automatically in each component that has an http request?

Also when the http request is done I want to show a message like "Done" or someting.

If anyone can provide me a solution for that I'll really appreciate, ty.

5 Answers

With angular 2+, Create a reusable util component

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-progress-mask',
  templateUrl: './progress-mask.component.html',
  styleUrls: ['./progress-mask.component.css']
})
export class ProgressMaskComponent implements OnInit {
  @Input() showProgress:boolean = false;
  constructor() { }

  ngOnInit() {
  }

}

The html part:

<div class="loadWrapper" *ngIf="showProgress">  
  <div class="loader"></div>  
</div>

the CSS part:

.loadWrapper {  
    background: rgba(0,0,0,0.3);  
    width: 100%;  
    height: 100%;  
    position: fixed;  
    top:0px;  
    left:0px;  
    z-index: 99999;  
}  
.loader {
    border: 5px solid #f3f3f3; /* Light grey */
    border-top: 5px solid #3d3e3f; /* gray */
    position: absolute;
    left: 50%;
    top: 50%;
    border-radius: 50%;
    width: 50px;
    height: 50px;
    animation: spin 2s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

Now insert this to your component

<app-progress-mask [showProgress]="showMask"></app-progress-mask>

Bind showMask of your component to the reusable util component

Related