Reputation: 713
I am trying to add a spinner to my application but the spinner is not appearing.
There are no errors appearing in the console or terminal, yet the spinner is not appearing.
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class LoaderService {
public status: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
display(value: boolean) {
this.status.next(value);
}
}
imported LoadService and added it to the providers array
import { LoaderService } from './services/loader.service';
export class AppComponent {
//for the spinner
showLoader: boolean;
//LoaderService is for the spinner
constructor(private loaderService: LoaderService) { }
//for the spinner
ngOnInit() {
this.loaderService.status.subscribe((val: boolean) => {
this.showLoader = val;
});
}
}
<router-outlet>
<div *ngIf="showLoader">
<mat-spinner></mat-spinner>
</div>
</router-outlet>
import { LoaderService } from '../services/loader.service';
export class SurveyresultsComponent implements OnInit {
constructor(private loaderService: LoaderService) { }
ngOnInit() {
//http call starts
this.loaderService.display(true);
//http call ends
this.loaderService.display(false);
}
}
Upvotes: 0
Views: 17561
Reputation: 11
In your Custom.component.ts class, you are calling below 2 statements one after the another, instead you have to use timeout
ngOnInit() {
//http call starts
this.loaderService.display(true);
//http call ends
setTimeout(() => {
this.loaderService.display(false);
},5000);
}
By executing this block, spinner will displayed for 5 Seconds.
Upvotes: 0
Reputation: 6578
I think you are calling your loader service in wrong way.
your loader code logic is
this.loaderService.display(true);
//http call ends
this.loaderService.display(false);
written in custom.component.ts and your HTML code for that is written in app.component.html
try using the same HTML code in custom.component.html or try adding
this.loaderService.display(true);
//http call ends
this.loaderService.display(false);
this logic in app.component.ts or else you could print showLoader value besides that div in app.component.html like {{showLoader}}
Upvotes: 1
Reputation: 1333
Looks like a scope issue. An instance of the AppComponent must be available for the subscribe function to use the component's variables. 'this' refers to the scope of the subscribe function.
export class AppComponent {
//for the spinner
showLoader: boolean;
//LoaderService is for the spinner
constructor(private loaderService: LoaderService) { }
//for the spinner
ngOnInit() {
let self=this;
this.loaderService.status.subscribe((val: boolean) => {
self.showLoader = val;
});
}
}
Upvotes: 1