Angular 7 - 从服务器获取更新到应用程序的最佳方式
Angular 7 - best way to get updates from the server to app
我正在为我的站点开发 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;
}
}
});
}
}
最好的形式是使用 SSE https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events 如果你的 API 响应 header 就像:
header('Cache-Control: no-cache');
header("Content-Type: text/event-stream\n\n");
你可以在 notificationService 中进行 getUpdates :
getUpdates(){
let source = new EventSource('http://serverip:port/get_mydata');
source.addEventListener('message', response => {
const response = JSON.parse(response);
return reponse;
});
}
并在您的 NotificationDropdownComponent 中进行更新
toBeUpdated(){
this.notificationService.getUpdates().subscribe( response => {
if (!response.error) {
if (response.notifications) {
this.notifications = response.notifications;
}
}
});
}
我正在为我的站点开发 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;
}
}
});
}
}
最好的形式是使用 SSE https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events 如果你的 API 响应 header 就像:
header('Cache-Control: no-cache');
header("Content-Type: text/event-stream\n\n");
你可以在 notificationService 中进行 getUpdates :
getUpdates(){
let source = new EventSource('http://serverip:port/get_mydata');
source.addEventListener('message', response => {
const response = JSON.parse(response);
return reponse;
});
}
并在您的 NotificationDropdownComponent 中进行更新
toBeUpdated(){
this.notificationService.getUpdates().subscribe( response => {
if (!response.error) {
if (response.notifications) {
this.notifications = response.notifications;
}
}
});
}