Advertisement
Guest User

Untitled

a guest
Jun 21st, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. import {
  2. Injectable,
  3. EventEmitter
  4. } from '@angular/core';
  5.  
  6.  
  7. declare var $: any;
  8. @Injectable({
  9. providedIn: 'root'
  10. })
  11. export class SignalRService {
  12. // Declare the variables
  13. private proxy: any;
  14. private proxyName: string = 'notifications';
  15. private connection: any;
  16. // create the Event Emitter
  17. public notificationReceived: EventEmitter < string > ;
  18. public connectionEstablished: EventEmitter < Boolean > ;
  19. public connectionExists: Boolean;
  20. constructor() {
  21. debugger;
  22. // Constructor initialization
  23. this.connectionEstablished = new EventEmitter < Boolean > ();
  24. this.notificationReceived = new EventEmitter < string > ();
  25. this.connectionExists = false;
  26. // create hub connection
  27. this.connection = $.hubConnection("http://localhost:51680");
  28. var jwt=localStorage.jwt;
  29. this.connection.qs= {'token' : 'Barer' + jwt}
  30. // create new proxy as name already given in top
  31. this.proxy = this.connection.createHubProxy(this.proxyName);
  32. // register on server events
  33. // call the connecion start method to start the connection to send and receive events.
  34. this.registerOnServerEvents();
  35. this.startConnection();
  36. }
  37.  
  38. public sendHello() {
  39. // server side hub method using proxy.invoke with method name pass as param
  40. this.proxy.invoke('Hello');
  41. }
  42. // check in the browser console for either signalr connected or not
  43. private startConnection(): void {
  44.  
  45. this.connection.start().done((data: any) => {
  46. console.log('Now connected ' + data.transport.name + ', connection ID= ' + data.id);
  47. this.connectionEstablished.emit(true);
  48. this.connectionExists = true;
  49. }).fail((error: any) => {
  50. console.log('Could not connect ' + error);
  51. this.connectionEstablished.emit(false);
  52. });
  53. }
  54.  
  55.  
  56. private registerOnServerEvents(): void {
  57. debugger;
  58. this.proxy.on('clickNotification', (data: string) => {
  59. console.log('received notification: ' + data);
  60. this.notificationReceived.emit(data);
  61. });
  62. }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement