Sithys
Sithys

Reputation: 3793

angular - show loading while rxjs subscription waits for data

I have a simple subscription inside my onInit:

ngOnInit(): void {
    this.subscription = timer(0, 5000).pipe(
        switchMap(() => this.monitoringService.getHeartbeats())
      ).subscribe(data => this.heartbeats = data.data);
}

but i'd like to show a simple loading bar, while the subscription gets data from the server. Is there any way to set a variable like this.loading to true at start and false when the data is fetched?

For completness, this is an example of heartbeats i get:

....
  {
    _id: 5e58595325c28e4470c90d45,
    customer: 5cab35ae9a39025a6b8cef7e,
    activeUsers: 11,
    usersLoggedIn: 7,
    terminals: [ [Object], [Object] ],
    heartbeatDate: 2020-02-28T00:05:39.277Z,
    __v: 0
  },
  {
    _id: 5e58593a25c28e4470c90d42,
    customer: 5cab35ae9a39025a6b8cef7e,
    activeUsers: 11,
    usersLoggedIn: 7,
    terminals: [ [Object], [Object] ],
    heartbeatDate: 2020-02-28T00:05:14.311Z,
    __v: 0
  },
  {
    _id: 5e5858aac78f000c70ac2468,
    customer: 5cab35ae9a39025a6b8cef7e,
    activeUsers: 11,
    usersLoggedIn: 7,
    terminals: [ [Object], [Object] ],
    heartbeatDate: 2020-02-28T00:02:50.575Z,
    __v: 0
  },
  {
    _id: 5e5858348b2d6d3d0c1d482e,
    customer: 5cab35ae9a39025a6b8cef7e,
    activeUsers: 11,
    usersLoggedIn: 7,
    terminals: [ [Object], [Object] ],
    heartbeatDate: 2020-02-28T00:00:52.306Z,
    __v: 0
  } 
....

Upvotes: 2

Views: 1629

Answers (1)

AliF50
AliF50

Reputation: 18809

Try:

ngOnInit(): void {
    this.subscription = timer(0, 5000).pipe(
        tap(() => this.loading = true),
        switchMap(() => this.monitoringService.getHeartbeats())
      ).subscribe(data => { 
                           this.heartbeats = data.data; 
                           this.loading = false;
       }, err => this.loading = false ); // handle error how you want, just turn loading off as well
}

Upvotes: 1

Related Questions