Display Spinner till API Response in angular 6

1820 views angular
4

I am new to Angular 6 and no experience in any version of angular previously & creating my website using angular 6, in which i have to display spinner till API Response is pending.I am using httpclient of angular 6 to call APIs. I want to show spinner for every API request. I searched on SO but didn't find answer of my question.Below is my component & services file.

/* 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;
  constructor(private data: DataService) { }
  ngOnInit() {
    this.data.getUsers().subscribe(data => {
      this.users$ = data; 
    });
  }
}

Can anyone please help me to solve this problem? Any help would be appreciated.

answered question

1 Answer

3

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
    ) { }
    userLogin() {

        this.spinnerService.show();
            console.log('logging in');
            this.eService.signIn(this.user_name, this.password)
            .subscribe(
                data => {
                    console.log(data);
                   this.spinnerService.hide();
                }

            );
        }

Live Demo

posted this

Have an answer?

JD

Please login first before posting an answer.