I noticed a very strange behavior in my Angular application

57 Views Asked by At

enter code hereSo I am using the data that I get from the getDashboardsSEE method in the service layer. The lines for accessing the data:

this.dashboardService.getDashboardsSSE().subscribe(data => {

  if(data.length > 0) {
    this.dashboards = data;
    this.currentDashboard = this.dashboards[0].id;
    this.communicationService.setDashboard(this.currentDashboard);  
    this.noDashboard = false;
  }
});

The getDashboardsSSE uses EventSource for getting the data. It first pushes all the stream to an array and then return this array as an observable. The getDashboardsSSE method:

    getDashboardsSSE(): Observable<any[]> {
    let dashboards = []
    return Observable.create((observer) => {
      let eventSource = new EventSource(this.sseUrl);
      eventSource.onmessage = (event) => {
        let dashboard = JSON.parse(event.data);
        dashboards.push(dashboard);
      };
      eventSource.onerror = (error) => {
        if(eventSource.readyState === 0) {
          console.log('The stream has been closed by the server');
          eventSource.close();
          observer.next(dashboards);
          observer.complete();
        } else {
          observer.error('Error: ' + error);
        }
      };

    });
  }

The problem here is that the page only renders when I click on something like pressing F12 or clicking on other clickable items in the page. Has anyone notices this behavior before. This doesn't happen when I use the get the data from the standard REST endpoint using the http object. Has anyone got this problem before and how did you work around it?

1

There are 1 best solutions below

6
On

It seems like you call getDashboardsSSE when an event happens? When do you trigger it?

Why not:

const dashboardObserver = this.dashboardService.getDashboardsSSE();
const subscription = dashboardObserver.subscribe(data => {
if(data.length > 0) {
    this.dashboards = data;
    this.currentDashboard = this.dashboards[0].id;
    this.communicationService.setDashboard(this.currentDashboard);  
    this.noDashboard = false;
  }
});