Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Injectable, NgZone } from '@angular/core';
- import { Subject } from 'rxjs';
- import { environment } from 'environments/environment';
- declare var $: any;
- @Injectable({
- providedIn: 'root'
- })
- export class SignalrWebsocketsService {
- private connection: any;
- private proxy: any;
- updateUsers$ = new Subject<any>();
- updateTag$ = new Subject<any>();
- constructor(private _ngZone: NgZone) {
- }
- createConnection(name: string) {
- let signalRServerPoint = environment.baseApiUrl;
- this.connection = $.hubConnection(signalRServerPoint);
- this.proxy = this.connection.createHubProxy('websockets');
- this.connection.stateChanged((change) => {
- if (change.newState === $.signalR.connectionState.connecting) {
- console.log("Conectando");
- }
- else if (change.newState === $.signalR.connectionState.connected) {
- console.log("Conectado");
- this.proxy.invoke("AddDispositivo", name);
- }
- else if (change.newState === $.signalR.connectionState.reconnecting) {
- console.log("Reconectando");
- this.connection.stop();
- }
- else if (change.newState === $.signalR.connectionState.disconnected) {
- console.log("Desconectado");
- setTimeout(function() {
- this.connection.start();
- }, 5000);
- }
- });
- this.proxy.on('updateDispositivos', (count, devices) => {
- this._ngZone.run(() => {
- var data = {
- count: count,
- list: devices
- }
- this.updateUsers$.next(data);
- });
- });
- this.proxy.on('updateTag', (tags) => {
- this._ngZone.run(() => {
- this.updateTag$.next(tags);
- });
- });
- }
- startConnection() {
- this.connection.start();
- }
- invokeProxy(method: string, ...params: any) {
- this.proxy.invoke(method, params);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement