angular中
angular中通过订阅.subscribe可以一直拿到服务端发送的数据
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
......
export class SseExampleComponent implements OnInit {
constructor(private http: HttpClient) {}
ngOnInit() {
this.http.get('http://your-sse-endpoint', {
observe: 'response',
responseType: 'text'
}).subscribe(event => {
if (event.type === HttpEventType.Response) {
// 链接
} else if (event.type === HttpEventType.Data) {
// 在这里处理接收到的数据
} else if (event.type === HttpEventType.Close) {
// 关闭
}
});
}
}
vue中
vue通过vue-sse来请求http长链接
- npm install vue-sse
- 挂载插件
import VueSSE from 'vue-sse';
Vue.use(VueSSE, {
// 可以在这里设置默认的URL和选项,如果需要的话
});
- 使用
this.$sse.listen('/heartbeat', (event, data) => {
// 当接收到服务器推送的数据时,处理数据
console.log('data:', data);
});