Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用RxJs和Angular 2来处理服务器发送的事件_Angular_Server Sent Events_Rxjs5 - Fatal编程技术网

使用RxJs和Angular 2来处理服务器发送的事件

使用RxJs和Angular 2来处理服务器发送的事件,angular,server-sent-events,rxjs5,Angular,Server Sent Events,Rxjs5,我试图在angular 2/RxJs应用程序中显示服务器发送的事件发出的值 后端通过服务器发送的事件定期向客户端发送单个字符串 我不知道如何处理angular 2/RxJs端的检索值 这是我的客户机(ng组件): 我只是注意到应用程序挂起了请求,页面上没有显示任何内容 我怀疑我使用map方法有问题,即.map(this.extractData) 我只想将传入的字符串添加到数组中,并在模板中显示该数组,该模板将随着字符串的出现而更新 有人能帮忙吗 编辑:以下是一个可行的解决方案(感谢Thierry

我试图在angular 2/RxJs应用程序中显示服务器发送的事件发出的值

后端通过服务器发送的事件定期向客户端发送单个字符串

我不知道如何处理angular 2/RxJs端的检索值

这是我的客户机(ng组件):

我只是注意到应用程序挂起了请求,页面上没有显示任何内容

我怀疑我使用map方法有问题,即
.map(this.extractData)

我只想将传入的字符串添加到数组中,并在模板中显示该数组,该模板将随着字符串的出现而更新

有人能帮忙吗

编辑:以下是一个可行的解决方案(感谢Thierry在下面的回答):

从'angular2/core'导入{Component,OnInit};
进口“rxjs/Rx”;
@组成部分({
选择器:“我的应用程序”,
模板:`我的第二个Angular 2应用程序
    字符串:{{s}
` }) 导出类AppComponent实现OnInit{ someStrings:string[]=[]; 恩戈尼尼特(){ let source=new EventSource('/interval sse observable'); source.addEventListener('message',aString=>this.someStrings.push(aString.data),false); } }
不能使用Angular2的Http类来处理服务器端事件,因为它基于XHR对象

您可以利用EventSource对象:

var source = new EventSource('/...');
source.addListener('message', (event) => {
  (...)
});
见以下文章:


    • 以下是一个工作示例:

      SSE服务

      import {Injectable} from '@angular/core';
      import {Observable} from 'rxjs/Observable';
      
      declare var EventSource;
      
      @Injectable()
      export class SseService {
      
          constructor() {
          }
      
          observeMessages(sseUrl: string): Observable<string> {
              return new Observable<string>(obs => {
                  const es = new EventSource(sseUrl);
                  es.addEventListener('message', (evt) => {
                      console.log(evt.data);
                      obs.next(evt.data);
                  });
                  return () => es.close();
              });
          }
      }
      
      从'@angular/core'导入{Injectable};
      从“rxjs/Observable”导入{Observable};
      声明var事件源;
      @可注射()
      出口类服务{
      构造函数(){
      }
      observeMessages(sseUrl:string):可观察{
      返回新的可观测值(obs=>{
      const es=新事件源(sseUrl);
      es.addEventListener('消息',(evt)=>{
      控制台日志(evt.data);
      obs.next(evt.data);
      });
      return()=>es.close();
      });
      }
      }
      
      AppComponent

      import {Component, OnDestroy, OnInit} from '@angular/core';
      import {SseService} from './shared/services/sse/sse.service';
      import {Observable, Subscription} from 'rxjs/Rx';
      
      @Component({
          selector: 'my-app',
          template: `<h1>Angular Server-Sent Events</h1>
          <ul>
              <li *ngFor="let message of messages">
                   {{ message }}
              </li>
          </ul>
          `
      })
      export class AppComponent implements OnInit, OnDestroy {
          private sseStream: Subscription;
          messages:Array<string> = [];
      
          constructor(private sseService: SseService){
          }
      
          ngOnInit() {
              this.sseStream = this.sseService.observeMessages('https://server.com/mysse')
                              .subscribe(message => {
                                  messages.push(message);
                              });
          }
      
          ngOnDestroy() {
              if (this.sseStream) {
                  this.sseStream.unsubscribe();
              }
          }
      }
      
      从'@angular/core'导入{Component,OnDestroy,OnInit};
      从“./shared/services/sse/sse.service”导入{SseService};
      从“rxjs/Rx”导入{可观察,订阅};
      @组成部分({
      选择器:“我的应用程序”,
      模板:`Angular服务器已发送事件
      
        {{message}}
      ` }) 导出类AppComponent实现OnInit、OnDestroy{ 私有流:订阅; 消息:数组=[]; 构造函数(专用sseService:sseService){ } 恩戈尼尼特(){ this.sseStream=this.sseService.observeMessages('https://server.com/mysse') .订阅(消息=>{ 消息。推送(消息); }); } 恩贡德斯特罗(){ if(this.sseStream){ this.sseStream.unsubscribe(); } } }
      要添加到,默认情况下,事件类型为“消息”。但是,根据服务器端实现,事件类型可以是类似('chat','log'等)的任何类型。 在我的例子中,来自服务器的前两个事件是“message”,其余的是“log”。我的代码如下所示

      var source=neweventsource('/…');
      source.addListener('message',message=>{
      (...)
      });
      source.addListener('log',log=>{
      (...)
      
      });

      嗨,蒂埃里,这是一个有点离题的问题:今天鼓励使用SSE吗?SSE是否将被http2取代?除了苏格兰和南方能源公司,还有更好的选择吗?我注意到一些浏览器根本不支持SSE…你能告诉我你是否能在angular 4上使用它吗?我使用来自'@angular/core'的import{Component,OnInit};并且找不到EventSource类。你能告诉我你是否安装了其他定制软件包吗?如果您能在github中共享完整的代码,请参考。谢谢。一点解释就好了,但我还是忍不住要提高投票率:)非常性感!不言自明,做得很好,阿巴赫。太好了,谢谢!你将如何将其添加到NGRX效果中?回答得很好!做得很好。。。
      var source = new EventSource('/...');
      source.addListener('message', (event) => {
        (...)
      });
      
      import {Injectable} from '@angular/core';
      import {Observable} from 'rxjs/Observable';
      
      declare var EventSource;
      
      @Injectable()
      export class SseService {
      
          constructor() {
          }
      
          observeMessages(sseUrl: string): Observable<string> {
              return new Observable<string>(obs => {
                  const es = new EventSource(sseUrl);
                  es.addEventListener('message', (evt) => {
                      console.log(evt.data);
                      obs.next(evt.data);
                  });
                  return () => es.close();
              });
          }
      }
      
      import {Component, OnDestroy, OnInit} from '@angular/core';
      import {SseService} from './shared/services/sse/sse.service';
      import {Observable, Subscription} from 'rxjs/Rx';
      
      @Component({
          selector: 'my-app',
          template: `<h1>Angular Server-Sent Events</h1>
          <ul>
              <li *ngFor="let message of messages">
                   {{ message }}
              </li>
          </ul>
          `
      })
      export class AppComponent implements OnInit, OnDestroy {
          private sseStream: Subscription;
          messages:Array<string> = [];
      
          constructor(private sseService: SseService){
          }
      
          ngOnInit() {
              this.sseStream = this.sseService.observeMessages('https://server.com/mysse')
                              .subscribe(message => {
                                  messages.push(message);
                              });
          }
      
          ngOnDestroy() {
              if (this.sseStream) {
                  this.sseStream.unsubscribe();
              }
          }
      }