角度:通过SignalR

时间:2019-07-11 13:27:06

标签: angular rxjs asp.net-core-mvc signalr eventemitter

我已在 Getting Started With SignalR Using ASP.NET Core And Angular 上使用以下方法将SignalR集成到了Angular(v8)项目中。在此示例中,使用了EventEmitter以便从服务器发射接收到的数据,但是我不确定是否有更好的方法将数据发射到其他组件(例如SubjectBehaviour等)。我使用EventEmitter来传递数据从子级到父级组件,并且之前使用SubjectBehaviour在同级组件之间传递数据。在这种情况下,我需要使用最佳方法。另一方面,我不确定EventEmitter的用法是否与将数据从Child传递到Parent组件的用法不同(我之前在Angular 5: Share data between sibling components using EventEmitter上使用过)。您能否也向我澄清一下?

service.ts:

@Injectable()  
export class SignalRService {  
  messageReceived = new EventEmitter<ChatMessage>();  
  connectionEstablished = new EventEmitter<Boolean>();

  constructor() {  
    this.registerOnServerEvents();  
    this.startConnection();  
  }

  private startConnection(): void {  
    this._hubConnection  
      .start()  
      .then(() => {  
        this.connectionEstablished.emit(true);  
      })
  }  

  private registerOnServerEvents(): void {  
    this._hubConnection.on('ReceiveMessage', (data: any) => {  
      this.messageReceived.emit(data);  
    });  
  }  
}  


component.ts:

export class ClockComponent { 

  constructor(private _signalRService: SignalRService, private _ngZone: NgZone) {  
      this.subscribeToEvents();
  }  

  private subscribeToEvents(): void {  
      this._signalRService.connectionEstablished.subscribe(() => {  
          this.canSendMessage = true;  
      });  

      this._signalRService.messageReceived.subscribe((message: GetClockTime) => { 
          this._ngZone.run(() => {  
              this.allMessages = message;  
          });  
      });  
  }  
}  

0 个答案:

没有答案