Advertisement
Guest User

Untitled

a guest
Jul 16th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. import { Injectable, NgZone } from '@angular/core';
  2. import { Subject } from 'rxjs';
  3. import { environment } from 'environments/environment';
  4.  
  5. declare var $: any;
  6.  
  7. @Injectable({
  8. providedIn: 'root'
  9. })
  10. export class SignalrWebsocketsService {
  11.  
  12. private connection: any;
  13. private proxy: any;
  14.  
  15. updateUsers$ = new Subject<any>();
  16. updateTag$ = new Subject<any>();
  17.  
  18. constructor(private _ngZone: NgZone) {
  19.  
  20. }
  21.  
  22. createConnection(name: string) {
  23. let signalRServerPoint = environment.baseApiUrl;
  24. this.connection = $.hubConnection(signalRServerPoint);
  25. this.proxy = this.connection.createHubProxy('websockets');
  26.  
  27. this.connection.stateChanged((change) => {
  28.  
  29. if (change.newState === $.signalR.connectionState.connecting) {
  30. console.log("Conectando");
  31. }
  32. else if (change.newState === $.signalR.connectionState.connected) {
  33. console.log("Conectado");
  34. this.proxy.invoke("AddDispositivo", name);
  35. }
  36. else if (change.newState === $.signalR.connectionState.reconnecting) {
  37. console.log("Reconectando");
  38. this.connection.stop();
  39. }
  40. else if (change.newState === $.signalR.connectionState.disconnected) {
  41. console.log("Desconectado");
  42. setTimeout(function() {
  43. this.connection.start();
  44. }, 5000);
  45. }
  46. });
  47.  
  48. this.proxy.on('updateDispositivos', (count, devices) => {
  49. this._ngZone.run(() => {
  50. var data = {
  51. count: count,
  52. list: devices
  53. }
  54. this.updateUsers$.next(data);
  55. });
  56. });
  57.  
  58. this.proxy.on('updateTag', (tags) => {
  59. this._ngZone.run(() => {
  60. this.updateTag$.next(tags);
  61. });
  62. });
  63. }
  64.  
  65. startConnection() {
  66. this.connection.start();
  67. }
  68.  
  69. invokeProxy(method: string, ...params: any) {
  70. this.proxy.invoke(method, params);
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement