Display Spinner till API Response in angular 6
For that purpose I would use http interceptor for checking certain events during http request. Let's have component which will have some loader and put that component on same level like router outlet or app component. From our interceptor we will communicate with service to tell our component whenever show loader or not.
There is simple angular 6 example for that: https://stackblitz.com/edit/angular-hgxcsu
If you insist on not installing any packages then use a boolean flag to tell if the loading has finished yet
Get a loading animation from https://loading.io/ to put in the loading section of the html
/* data.services.ts */
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
getUsers() {
return this.http.get('https://jsonplaceholder.typicode.com/users')
}
}
/* users.component.ts *
import { Component, OnInit } from '@angular/core';
import {DataService} from '../data.service';
import { Observable } from 'rxjs';
@Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {
users: Object; // <-- Do not use $ at the end of a variable unless it is an observable
loading = true;
constructor(private data: DataService) { }
ngOnInit() {
this.data.getUsers().subscribe(data => {
this.users = data;
this.loading = false;
});
}
}
<div *ngIf="loading else loaded">
loading ...
</div>
<ng-template #loaded>
<div *ngFor="let user of users">{{user.name}}</div>
</ng-template>
You can use ng4-loading-spinner
Execute npm i ng4-loading-spinner --save
Import module to your application root module
import { Ng4LoadingSpinnerModule } from 'ng4-loading-spinner';
Make an import entry
imports: [ Ng4LoadingSpinnerModule.forRoot() ]
Include spinner component to your root level component.
<ng4-loading-spinner> </ng4-loading-spinner>
use show()
and hide()
inside subscribe
callback
import { Ng4LoadingSpinnerService } from 'ng4-loading-spinner';
constructor(
private spinnerService: Ng4LoadingSpinnerService,
private data: DataService
) { }
ngOnInit() {
this.spinnerService.show();//show the spinner
this.data.getUsers().subscribe(data => {
this.users$ = data;
this.spinnerService.hide();//hide the spinner if success
},
(error)=>this.spinnerService.hide();//hide the spinner in case of error
);
}}
Live Demo