Poul
Poul

Reputation: 31

Angular 7 - best way to get updates from the server to app

I'm developing angular7 messages service (user to user) for my site. At the moment I'm getting updates from the server (Yii2 REST API) each 3 min by the interval. (code is below)

Is it an appropriate practice? What is the most convenient way to get updates from the server?

export class NotificationDropdownComponent implements OnInit {

  public notifications;
  constructor(
    private notificationService: NotificationService,
  ) {  }

  ngOnInit() {
    this.getNotSeen();
  }

  getNotSeen():void {
    this.notificationService.getUpdates()
      .subscribe( response => {
        if (!response.error) {
          if (response.notifications) {
            this.notifications = response.notifications;
          }
          this.toBeUpdated();
        }
      });
  }

  toBeUpdated(){
    interval(3*60*1000)
      .pipe(flatMap(()=> this.notificationService.getUpdates()))
      .subscribe( response => {
        if (!response.error) {
          if (response.notifications) {
            this.notifications = response.notifications;
          }
        }
      });
  }
}

Upvotes: 1

Views: 755

Answers (1)

Evandro Mendes
Evandro Mendes

Reputation: 126

Best form is use SSE https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events if your API response with header like as:

 header('Cache-Control: no-cache');
  header("Content-Type: text/event-stream\n\n");

you can make the getUpdates in notificationService :

getUpdates(){
 let source = new EventSource('http://serverip:port/get_mydata');
 source.addEventListener('message', response => {
   const response = JSON.parse(response);    
   return reponse;    
});

}

And toBeUpdated in your NotificationDropdownComponent

toBeUpdated(){
   this.notificationService.getUpdates().subscribe( response => {
        if (!response.error) {
          if (response.notifications) {
            this.notifications = response.notifications;
          }
        }
      });
}

Upvotes: 1

Related Questions