Monday, 20 November 2017

Apply loader in angular 4 using shared service and component.



1. Create a shared service and Import "Subject" from 'rxjs/Subject' like this=>


import { Injectable } from '@angular/core';
import {Subject} from 'rxjs/Subject';

@Injectable()
export class PreloaderService {

showLoaderFull: Subject<boolean> = new Subject<true>();
showLoaderSmall: Subject<boolean> = new Subject<true>();

getShowLoader() {
return this.showLoaderFull.asObservable();
}
showPreloader(preloaderType = 'full'): void {
if (preloaderType === 'full') {
this.showLoaderFull.next(true);
} else if (preloaderType === 'small') {
this.showLoaderSmall.next(true)
}
}
hidePreloader(preloaderType = 'full'): void {
if (preloaderType === 'full') {
this.showLoaderFull.next(false);
} else if (preloaderType === 'small') {
this.showLoaderSmall.next(false);
}
}
}



2. Create a Component and call this shared service in the same component like this=>


import { Component } from '@angular/core';
import {PreloaderService} from '../../../services/preloader.service';

@Component({
selector: 'preloader',
styleUrls: ['preloader.component.css'],
templateUrl: './preloader.component.html'
})
export class PreloaderComponent {
showloader = false;
constructor(public preloaderService: PreloaderService) {
preloaderService.getShowLoader().subscribe(
res =>this.showloader = res)
}
}

3. Create an Html for loader like this or what you want =>


<div class="preloader-full" *ngIf="showloader">
<svg class="circular" viewBox="25 25 50 50">
<circle class="path" cx="50" cy="50" r="20" fill="none"
stroke-width="2" stroke-miterlimit="10" />
</svg>
</div>


4. Show a loader(call this shared service in the component) like this=>


import { Component } from '@angular/core';
import {PreloaderService} from '../../../services/preloader.service';

@Component({
selector: 'preloader',
styleUrls: ['preloader.component.css'],
templateUrl: './preloader.component.html'
})
export class ShowloaderComponent {
constructor(public preloaderService: PreloaderService) {
preloaderService.showPreloader();
}
}


5. Hide a loader(call this shared service in the component) like this =>



import { Component } from '@angular/core';
import {PreloaderService} from '../../../services/preloader.service';

@Component({
selector: '..selectorname',
styleUrls: ['....css'],
templateUrl: '....html'
})
export class HideloaderComponent {
constructor(public preloaderService: PreloaderService) {
preloaderService.hidePreloader();
}
}










No comments:

Post a Comment