Angular4 Observable订阅ServiceStack服务器事件

时间:2017-06-30 19:22:01

标签: angular servicestack rxjs angular2-observables

我们有一个Angular 1应用程序,它每隔几秒就会轮询一次ServiceStack Web API,并且作为升级到Angular 4的一部分,我希望将其换成对ServiceStack服务器事件的rxjs可观察订阅

有没有人知道这是否可行,或者我应该只为我的订阅使用ss-utils?

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

对于Angular4,建议使用TypeScript Server Events Client servicestack-client npm package,提供对所有ServiceStack高级服务器事件API的访问。

您可能会为您感兴趣的每个事件创建可观察对象,例如:

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

但我对RxJS不太熟悉,知道这是否是使用RxJS的最佳方法。