de albuquerque frank
de albuquerque frank

Reputation: 197

Loading spinner does not appear with delay

Loading spinner should appear and disapper after a delay but it doesn't appear at all, but if i remove the line "this.isLoading = false" the spinner is showing but doesn't disappear !

 const myObservable = of("foobar");

    myObservable.subscribe((value) => {

      this.isLoading = true,
        delay(5000),
       // If i remove the line below the spinner is showing
        this.isLoading = false

      console.log(value);  
    });

Upvotes: 0

Views: 282

Answers (2)

Barremian
Barremian

Reputation: 31115

Instead of a fixed time, I'd say it's better to use tap and finalize operators to control the spinner's visibility.

Try the following

Controller

isLoading = false;

myObservable.pipe(
  tap(_ => this.isLoading = true),        // <-- triggered as soon the subscription is invoked
  finalize(_ => this.isLoading = false)   // <-- triggered when the observable completes
).subscribe((value) => {
  console.log(value);  
});

Template

<ng-container *ngIf="isLoading">
  <!-- show spinner -->
</ng-container>

Upvotes: 1

Timothy
Timothy

Reputation: 3593

delay() is rxjs operator. Use as follows:

of("foobar").pipe(
  tap(_ => {this.isLoading = true}),
  delay(5000),
  tap(_ => {this.isLoading = false}),
).subscript()

Upvotes: 2

Related Questions