Search code examples
angularsignalrsignalr-hub

SignalR with Angular 4


I want to connect to a SignalR Hub and retrieve data by using Angular 4. I would appreciate if you could provide me with a sample as how to achieve this.


Solution

  • here I would like to provide you with SignlR service which i have used in my project. Hope this helps you understand.

    import { CommonService } from './commonService';
    import { AuthSettings } from '../authSettings';
    import { Injectable, EventEmitter } from '@angular/core';
    
    declare const $: any;
    @Injectable()
    export class SignalRService {
      private connectionId;
      private authData;
      private signalRConnectionId;
      private proxy: any;
      private connection: any;
      private tryingToReconnect = false;
      public ExpiredBidStatus: EventEmitter<any>;
      public ActivatedBid: EventEmitter<any>;
      public Notification: EventEmitter<any>;
    
      constructor(private commonSvc: CommonService) {
        this.ActivatedBid = new EventEmitter<any>();
        this.ExpiredBidStatus = new EventEmitter<any>();
        this.Notification = new EventEmitter<any>();
      }
    
      public initialize(): void {
        this.connection = $.hubConnection(AuthSettings.apiServiceBaseUri);
        this.proxy = this.connection.createHubProxy('crowneStockHub');
        this.setToken();
    
        this.proxy.on('broadcastExpiredBidStatus', (bidId) => {
          this.ExpiredBidStatus.emit(bidId);
        });
    
        this.proxy.on('broadcastActivatedBid', (bid) => {
          console.log('activated bid');
          this.ActivatedBid.emit(bid);
        });
    
        this.proxy.on('broadcastNotification', (notification) => {
          console.log('notification');
          console.log(notification);
          this.Notification.emit(notification);
        });
    
        this.proxy.on('broadcastTimeOut', () => {
          this.initialize();
        });
    
        this.stopConnection();
    
        this.connection.start().done((data: any) => {
          console.log('Now connected');
          this.connectionId = this.connection.id;
          this.commonSvc.signalRConnectionId = this.connectionId;
        }).fail((error: any) => {
          console.log('Could not connect ' + error);
    
        });
    
        this.connection.reconnecting(() => {
          this.tryingToReconnect = true;
        });
    
        this.connection.reconnected(() => {
          this.tryingToReconnect = false;
        });
        this.connection.error((error) => {
          this.initialize();
        });
        this.connection.disconnected(() => {
          if (this.tryingToReconnect) {
            setTimeout(() => {
              this.initialize();
            }, 5000);
    
          }
        });
    
      }
    
      setToken() {
        this.authData = window.localStorage.getItem('authorizationData');
        if (this.authData) {
          const token = this.authData.token;
          $.signalR.ajaxDefaults.headers = { Authorization: 'Bearer ' + token };
        }
      };
    
      stopConnection() {
        this.connection.stop();
      };
    
      getConnection() {
        return this.connectionId;
      };
    }