Angular 7-从服务器到应用程序获取更新的最佳方法

时间:2019-03-13 13:39:18

标签: angular api server updates

我正在为我的站点开发angular7消息服务(用户到用户)。 目前,我每隔3分钟从服务器(Yii2 REST API)获取更新。 (代码在下面)

这是适当的做法吗?从服务器获取更新的最便捷方法是什么?

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 :(得分:0)

如果您的API响应的标头如下所示,最好的形式是使用SSE https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

static/images/xyz-headshots.txt

您可以在NotificationService中进行getUpdates

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

}

在NotificationDropdownComponent中要更新

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