We have an Angular 1 app that polls a ServiceStack web API every few seconds and as part of the upgrade to Angular 4 I'd like to swap this out for a rxjs observable subscription to ServiceStack's Server Events.
Does anyone know if this is possible or should I just be using ss-utils for my subscription?
let serverEvent$ = Observable.create(
(observer) => {
let eventSource = this.sseService.createEventSource('http://localhost:8080/servereventapi');
eventSource.onmessage = (event) => {
this.zone.run(() => observer.next(JSON.parse(event.data)));
};
eventSource.onerror = (error) => observer.error(error);
});
//subscribe to the event
For Angular4 it's recommended to use TypeScript Server Events Client in the servicestack-client npm package which provides access to all of ServiceStack high-level Server Events API.
You could potentially create observables for each of the events you're interested in, eg:
var onMessage, onException, onJoin, CustomMessage;
let onMessage$ = Observable.create((observer) => {
onMessage = (msg:ServerEventMessage) => {
this.zone.run(() => observer.next(msg));
};
onException = (e:Error) => observer.error(error);
}
let onJoin$ = Observable.create((observer) => {
onJoin = (msg:ServerEventJoin) => {
this.zone.run(() => observer.next(msg));
};
}
let customMessage$ = Observable.create((observer) => {
CustomMessage = (msg:CustomMessage) => {
this.zone.run(() => observer.next(msg));
};
}
const client = new ServerEventsClient("/", channels, {
handlers: {
onConnect: (sub:ServerEventConnect) => { // Successful SSE connection
console.log("You've connected! welcome " + sub.displayName);
},
onJoin,
onMessage,
CustomMessage
},
onException
})
.start();
But I'm not familiar enough with RxJS to know if this is the best way to use RxJS.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.