Angular 7 - лучший способ получать обновления с сервера на приложение - PullRequest
0 голосов
/ 13 марта 2019

Я разрабатываю службу сообщений angular7 (от пользователя к пользователю) для своего сайта.В данный момент я получаю обновления с сервера (Yii2 REST API) каждые 3 минуты с интервалом.(код ниже)

Это подходящая практика?Какой самый удобный способ получать обновления с сервера?

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;
          }
        }
      });
  }
}

1 Ответ

0 голосов
/ 13 марта 2019

Лучшей формой является использование SSE https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events, если ваш ответ API с заголовком похож на:

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

вы можете сделать getUpdates в уведомлении службы:

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

}

И toBeUpdated в вашем уведомленииDropdownComponent

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